2012-07-25 52 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

相关问题