-1

我正在尝试读取我之前编写的程序中的两个文件,但它总是失败。

char line[BUFSIZ];
FILE *fp2=freopen("source.dat","r");

if(fp2==NULL)
printf("Problm opening: source.dat");

FILE *fp3=freopen("result.dat", "r");

if(fp3==NULL)
printf("Problm opening: result.dat");
char line2[BUFSIZ];
int len;

while( (fgets(line2, BUFSIZ, fp2) != NULL) && (fgets(line, BUFSIZ, fp3) != NULL)) {
len=strlen(line);
if( line[len - 1] == '\n' ) line[len-1] = '\0'; len=strlen(line2);
if( line2[len - 1] == '\n' ) line2[len-1] = '\0';

rename(line, line2);
}

我不知道为什么,我知道我的程序写了我想打开的两个文件。它只是没有通过while循环。

4

2 回答 2

0

这段代码对我有用,显然应该和你的一样,除非另有说明。

第一个注释显然是正确的:-)

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main(void)
{
       char line[2][BUFSIZ];
       FILE *fp[2];
       char *file[2] = { "source.dat", "result.dat" };
       int  f, finished = 0;

       // Any pointers to source and result must be flushed and closed at this point,
       // i.e. if this same program has created the files, it must now close them.

       for (f = 0; f < 2; f++)
       {
           if (NULL == (fp[f] = fopen(file[f],"r")))
           {
               fprintf(stderr, "Error opening %s\n", file[f]);
               exit(-1);
           }
       }

       while(!finished)
       {
           int len;
           for (f = 0; f < 2 && (!finished); f++)
           {
               if (NULL == fgets(line[f], BUFSIZ, fp[f]))
               {
                   fprintf(stderr, "NULL on %s\n", file[f]);
                   finished = 1;
                   break;
               }
               if (feof(fp[f]))
               {
                   fprintf(stderr, "end of %s\n", file[f]);
                   finished = 1;
                   break;
               }
               len = strlen(line[f]);

               // if one of the file contains an empty line, program might crash
               if (0 == len)
               {
                   fprintf(stderr, "empty line in %s\n", file[f]);
                   finished = 1;
                   break;
               }
               if ('\n' == line[f][len-1])
                   line[f][len-1] = 0x0;
           }
           if (finished)
              break;
           fprintf(stderr, "Rename(%s, %s)\n", line[0], line[1]);
           // rename(line, line2);
      }
      for (f = 0; f < 2; f++)
         fclose(fp[f]);

      return 0;
}
于 2013-02-07T00:01:03.780 回答
0

freopen接受 3 个参数,即文件名、模式和FILEStream 对象。因此,要重新打开文件,它应该已经打开。如果我们调用 afreopen作为第一次调用,运行时可能会抛出未初始化访问的异常。

修改代码如下

    fp2 = fopen("source.dat", "r");
    fp3 = fopen("result.dat", "r");

我能够毫无问题地运行您的代码,并且控制继续超出 while 循环。存储在第一个文件中的文件被重命名为存储在第二个文件中的名称,我认为这是您程序的目标。

于 2013-02-07T00:01:28.923 回答