[英]Copying data from one text file to another in C
我正在编写一个基本程序,该程序将从现有文本文件中复制字符串并将文本复制到新文本文件中。 我快到了,但是有几个小问题。 首先,我将复制后的文本行输出到屏幕上,它在字符串后给了我3个随机字符。 我想知道为什么会这样。 另外,程序正在创建新的文本文件,但未将字符串放入文件中。
这是我的代码:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
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;
}
该程序的修改后的版本可以完成以下任务:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
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;
}
在strcpy中,sec和dest的顺序相反
同样理想情况下,我不会复制而是连接到缓冲区。
您需要更改:
while(fgets(content, strlen(content), fp1) !=NULL)
您需要数组content
的sizeof
,而不是长度。
while(fgets(content, sizeof(content), fp1) !=NULL)
即使您在使用content
之前已经初始化了content
, strlen()
也会返回0,并且您将不会从文件中读取任何内容。
另外,如果要在写入新文件时重新读取输入文件,则需要fclose()
输入文件并fopen()
或rewind()
。
您在此使用的是:_ fprintf(fp2,newcontent); _
并且“ fprintf”的签名为int fprintf(FILE * stream,const char * format,...); 你想念
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.