似乎没有让fgetc第二次读取文件

时间:2012-07-25 13:46:37

标签: c fgetc

我正在重新打开并读取文件SORTED.txt,从第一次使用后关闭它 - 复制另一个文件的所有内容,UNSORTED.txt。 从UNSORTED.txt复制后,我想计算我复制的行数(作为一个单独的过程,而不是在复制过程中)。似乎fegtc()第二次没有指向文件的开头(SORTED.txt),因此行的值保持为初始化为0的值。另外,一般来说,我可以获得重新开始吗? 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);

2 个答案:

答案 0 :(得分:3)

您正在以"w"(写入)模式打开文件:

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

但是从中读取:

    j = fgetc(s);

您可能打算在阅读模式下打开它:

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

答案 1 :(得分: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;
}