【发布时间】:2025-11-20 17:40:01
【问题描述】:
我正在编写一个从现有文本文件复制字符串并将文本复制到新文本文件中的基本程序。我快到了,但我遇到了一些小问题。首先,我在复制后将文本行输出到屏幕上,它在字符串后面给了我 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;
}
【问题讨论】: