我正在编写一个基本程序,从现有的文本文件复制一个字符串,并将文本复制到一个新的文本文件中。我快到了,但我有一些小问题。首先,我在复制后将文本行输出到屏幕上,它在字符串后给了我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;
}

最佳答案

你需要改变:

while(fgets(content, strlen(content), fp1) !=NULL)

你需要的是sizeof数组,而不是长度。
while(fgets(content, sizeof(content), fp1) !=NULL)

即使在使用之前初始化了content,也会返回0,并且不会从文件中读取任何内容。
此外,如果您想在写入新文件时重新读取输入文件,则需要content输入文件并strlen()它或fclose()它。

关于c - 在C中将数据从一个文本文件复制到另一个,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/8333869/

10-09 06:06
查看更多