使用文件处理复制文本文件的内容

时间:2014-08-11 17:40:29

标签: c file-io

我创建了一个名为" test.txt"的文本文件。然后执行此程序以复制" test.txt"的内容到" file.txt"。但是在打开文件本身时显示错误,即fr==NULL为真。

该计划有什么问题?

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main()
{
   int i,count=0;
   char ch;
   FILE *fw,*fr;
   fw = fopen("file.txt", "a+");
   fr = fopen("test.txt", "r+");
   fseek(fr,0,SEEK_SET);
   if(fr==NULL)
   {
     printf("Error while opening the file.\n");
     exit(0);
   }
   while((ch=getc(fr))!=EOF)
   {
     putc(ch,fw);
   }
   fclose(fw);
   fclose(fr);
   return 0;
}

1 个答案:

答案 0 :(得分:0)

如果fopen返回NULL,请检查errno的值,例如包括<errno.h>并使用perror("Error while opening the file");代替printf语句。