從第一次使用關閉它後,我重新打開並讀取一個文件SORTED.txt - 複製另一個文件UNSORTED.txt的所有內容。 從UNSORTED.txt複製後,我想要統計我複製的行數(作爲單獨的過程,而不是在複製過程中)。似乎fegtc()並沒有指向文件的開頭(SORTED.txt)第二次,因此線的值仍然是初始化爲0的值。另外,通常,我可以獲得重新指定fgetc()完成後沒有關閉並重新打開該文件?看起來似乎得到fgetc第二次讀取文件的工作
感謝您的幫助。
乾杯!
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);
'j'是如何聲明的? – cnicutar 2012-07-25 13:50:13
j被聲明爲int – ceod 2012-07-25 13:52:21
使用'rewind(s)'回到文件的開頭[參考鏈接](http://www.cplusplus.com/reference/clibrary/cstdio/rewind/) – rkyser 2012-07-25 13:54:54