0

我正在重新打开并读取一个文件 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);
4

2 回答 2

3

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

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

但从中读取:

    j = fgetc(s);

您可能打算以读取模式打开它:

s = fopen("./TEXTFILES/SORTED.txt", "r");
                                    ^^^
于 2012-07-25T13:52:56.683 回答
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;
}
于 2012-07-25T14:21:40.490 回答