I'm reopening and reading a file, SORTED.txt, after closing it from its first time use - copying all the contents of another file, UNSORTED.txt. After copying from UNSORTED.txt, I wanted to count the number of lines of what I've copied (as a seperate process, and not during the copy process). It seems that fegtc() does not point at the beginning of the file (SORTED.txt) the second time over, hence the value of lines remains as what it was initialized as, 0. Also, in general, can I get the repointing of fgetc() done without closing and reopening the file in consideration?
Grateful for any help.
Cheers!
f = fopen("./TEXTFILES/UNSORTED.txt", "w");
if (f == NULL){
printf("ERROR opening file\n");
return 100;
}
for (i=0; i<1000000; i++){
fprintf(f, "%d\n", (23*rand()-rand()/13));
}
fclose(f);
f = fopen("./TEXTFILES/UNSORTED.txt", "r");
if (f == NULL){
return 100;
}
s = fopen("./TEXTFILES/SORTED.txt", "w");
if (s == NULL){
return 101;
}
while(1){
j = getc(f);
if (j == EOF) break;
fputc(j, s);
}
fclose(f);
//Closed source file. Read number of lines in target file.
fclose(s);
s = fopen("./TEXTFILES/SORTED.txt", "w");
j = 0;
while(1){
j = fgetc(s);
if (j == EOF) break;
if (j == '\n') lines++;
}
fclose(s);
printf("\n%d\n", lines);