在C中将数据从一个文本文件复制到另一个文本文件
我正在编写一个基本程序,它从现有的文本文件中复制一个字符串,并将文本复制到一个新的文本文件中。 我快到了,但我有一些小问题。 首先,我在复制后将文本行输出到屏幕,它在字符串后面给我3个随机字符。 我想知道为什么会这样。 此外,程序正在创建新的文本文件,但不将字符串放入文件中。
这是我的代码:
#include #include #include int main(void) { char content[80]; char newcontent[80]; //Step 1: Open text files and check that they open// FILE *fp1, *fp2; fp1 = fopen("details.txt","r"); fp2 = fopen("copydetails.txt","w"); if(fp1 == NULL || fp2 == NULL) { printf("Error reading file\n"); exit(0); } printf("Files open correctly\n"); //Step 2: Get text from original file// while(fgets(content, strlen(content), fp1) !=NULL) { fputs (content, stdout); strcpy (content, newcontent); } printf("%s", newcontent); printf("Text retrieved from original file\n"); //Step 3: Copy text to new file// while(fgets(content, strlen(content), fp1) !=NULL) { fprintf(fp2, newcontent); } printf("file created and text copied to it"); //Step 4: Close both files and end program// fclose(fp1); fclose(fp2); return 0; }
你需要改变:
while(fgets(content, strlen(content), fp1) !=NULL)
你需要数组content
的sizeof
,而不是长度。
while(fgets(content, sizeof(content), fp1) !=NULL)
即使你在使用它之前初始化了content
, strlen()
也会返回0,你就不会从文件中读取任何内容。
此外,如果要在编写新文件时重新读取输入文件,则需要fclose()
输入文件和fopen()
它或rewind()
它。
在strcpy中,sec和dest的顺序相反
理想情况下,我也不会复制,而是连接到缓冲区。
这个程序的修改版本可以完成这项工作:
#include #include #include int main(void) { char content[80]; //Step 1: Open text files and check that they open// FILE *fp1, *fp2; fp1 = fopen("details.txt","r"); fp2 = fopen("copydetails.txt","w"); if(fp1 == NULL || fp2 == NULL) { printf("\nError reading file\n"); exit(0); } printf("\nFiles open correctly\n"); //Step 2: Get text from original file// while(fgets(content, sizeof(content), fp1) !=NULL) { fprintf(fp2, "%s", content); } printf("File created and text copied to it\n\n"); //Step 4: Close both files and end program// fclose(fp1); fclose(fp2); return 0; }
你用过这个:_ fprintf(fp2,newcontent); _
并且“fprintf”的签名是int fprintf(FILE * stream,const char * format,…); 你错过了