在C程序中复制文件,但文件为空

我正在尝试将文件test1.mal的内容复制到output.txt并且程序说它正在这样做并且所有内容都编译,但是当我打开output.txt文件时,它是空白的……有人能说出来吗我哪里出错了?

 #include  #include  #include  int main(void) { char content[255]; char newcontent[255]; FILE *fp1, *fp2; fp1 = fopen("test1.mal", "r"); fp2 = fopen("output.txt", "w"); if(fp1 == NULL || fp2 == NULL) { printf("error reading file\n"); exit(0); } printf("files opened correctly\n"); while(fgets(content, sizeof (content), fp1) !=NULL) { fputs(content, stdout); strcpy (content, newcontent); } printf("%s", newcontent); printf("text received\n"); while(fgets(content, sizeof(content), fp1) !=NULL) { fprintf(fp2, "output.txt"); } printf("file created and text copied\n"); //fclose(fp1); //fclose(fp2); //return 0; } 

您正在将文件复制到标准输出:

 fputs(content, stdout); 

必须被替换

 fputs(content, fp2); 

或者,当您使用fprintf在输出文件中写入时,文件的光标已经在最后。 你可以使用带有SEEK_SET的fseek()将它作为开头。

您只需要一个缓冲区即可从输入文件中读取并将其写入输出文件。 并且您需要在最后关闭文件以确保数据被刷新。

 #include  #include  #include  int main(int argc, char** argv) { char content[255]; FILE *fp1, *fp2; fp1 = fopen("test1.mal", "r"); fp2 = fopen("output.txt", "w"); if(fp1 == NULL || fp2 == NULL){ printf("error reading file\n"); exit(0); } printf("files opened correctly\n"); // read from input file and write to the output file while(fgets(content, sizeof (content), fp1) !=NULL) { fputs(content, fp2); } fclose(fp1); fclose(fp2); printf("file created and text copied\n"); return 0; } 

首先,你应该记住,在意识形态上更真实的是在这里使用“rb”,“wb”。 当输入存在时,您必须将字节从一个文件复制到另一个文件。

 #include  int main() { freopen("input.txt", "rb", stdin); freopen("output.txt", "wb", stdout); unsigned char byte; while (scanf("%c", &byte) > 0) printf("%c", byte); return 0; } 

你把文件读到最后,写到stdout。 当你尝试进入第二个循环再次读取它时…你什么也得不到,因为你已经读过整个文件了。 尝试rewindfseek回到开头。 或者只是重新打开文件。 换句话说,只需添加:

 rewind(fp1); 

在第二个while循环之前。