2012-07-25 50 views
0

從第一次使用關閉它後,我重新打開並讀取一個文件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); 
+1

'j'是如何聲明的? – cnicutar 2012-07-25 13:50:13

+0

j被聲明爲int – ceod 2012-07-25 13:52:21

+0

使用'rewind(s)'回到文件的開頭[參考鏈接](http://www.cplusplus.com/reference/clibrary/cstdio/rewind/) – rkyser 2012-07-25 13:54:54

回答

2

聽起來就像你已經想通了!但是,自從我把這個例子放在一起的努力之後,我想我會把它發佈。

#include <stdio.h> 

int main() 
{ 
    FILE * f; 
    FILE * s; 
    int i, j; 
    int lines = 0; 

    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)); 
    } 

    s = fopen("./TEXTFILES/SORTED.txt", "w+"); 
    if (s == NULL){ 
     fclose(f); // cleanup and close UNSORTED.txt 
     return 101; 
    } 

    // rewind UNSORTED.txt here for reading back 
    rewind(f); 

    while(1){ 
     j = getc(f); 
     if (j == EOF) break; 
     fputc(j, s); 
    } 

    // done with UNSORTED.txt. Close it. 
    fclose(f); 

    // rewind SORTED.txt here for reading back 
    rewind(s); 
    j = 0; 

    while(1){ 
     j = fgetc(s); 
     if (j == EOF) break; 
     if (j == '\n') lines++; 
    } 

    fclose(s); 

    printf("\n%d\n", lines); 

    return 0; 
} 
+0

謝謝隊友!我只是爲了我的目的添加了倒帶。 – ceod 2012-07-25 14:25:34

3

您正在打開的文件中"w"(寫入)模式:

s = fopen("./TEXTFILES/SORTED.txt", "w"); 

但是從中讀取:

j = fgetc(s); 

你可能意味着在讀模式下打開它:

s = fopen("./TEXTFILES/SORTED.txt", "r"); 
            ^^^ 
+0

啊。它適用於「r」。我在「w」中使用過它,因爲我想在同一階段寫入/覆蓋。我必須在「r」模式後關閉它,然後用「w」重新打開。任何其他方式去解決它? – ceod 2012-07-25 13:56:40

+0

查看「參數」部分[此處](http://www.cplusplus.com/reference/clibrary/cstdio/fopen/)。您應該可以使用「w +」讀取和寫入新文件。但是如果文件已經存在,它會覆蓋它。 – rkyser 2012-07-25 13:59:14

+0

謝謝,但w +不適合我。 – ceod 2012-07-25 14:04:27