PDA

View Full Version : Reading and writing from the same file


BWiz
10-27-2009, 04:55 AM
Hey guys, I have this sample code which I pieced together to test a method which I will be implementing on my larger project. Anyway, the program generates 10 random numbers and stores it in a file. Then, it attempts to read from the same file. Instead of reading, however, it just gets stuck in an infinite loop. Any suggestions? Thanks.



#include <stdio.h>
#include <stdlib.h>

int main(void) {
srand(time());
FILE* handler = fopen("sample.txt", "w+");
int i;
for(i = 0; i < 10; i++) {
fprintf(handler, "%d\n", rand()*10);
}

while(!feof(handler)) {
int obj;
fscanf(handler, "%d", &obj);
printf("el -> %d\n", obj);
}

fclose(handler);


return EXIT_SUCCESS;
}



EDIT::

Nvm, solved it. It seems that you need to use seperate file handlers. So this code works:


#include <stdio.h>
#include <stdlib.h>

int main(void) {
srand(time());
FILE* handler = fopen("sample.txt", "w");
int i;
for(i = 0; i < 10; i++) {
fprintf(handler, "%d\n", rand()*10);
}

fclose(handler);

handler = fopen("sample.txt", "r");

while(!feof(handler)) {
int obj;
fscanf(handler, "%d", &obj);
printf("el -> %d\n", obj);
}

fclose(handler);


return EXIT_SUCCESS;
}


I would prefer using the same file handler, anybody know a way to do this? Thanks.

abduraooft
10-27-2009, 09:02 AM
I would prefer using the same file handler, anybody know a way to do this?
rewind() (http://irc.essex.ac.uk/www.iota-six.co.uk/c/i3_rewind_fputc_fputs.asp)

BWiz
10-28-2009, 01:54 AM
Nice, thanks!