复制从一个文本文件中的数据到另一个用C [英] Copying data from one text file to another in C
问题描述
我在写一个基本的程序,复制从现有的文本文件,并复制文字到一个新的文本文件中的字符串。我几乎没有,但我有几个小问题。首先,我输出文本到屏幕的复制和它给了我后弦3随机字符之后的行。我想知道为什么发生这种情况。此外,程序是创建新的文本文件,但不把串入文件
下面是我的code:
的#include<&stdio.h中GT;
#包括LT&;&string.h中GT;
#包括LT&;&stdlib.h中GT;INT主要(无效)
{
炭含量[80];
焦炭newcontent [80];//第1步:打开文本文件,并检查他们打开//
FILE * FP1,FP2 *;
FP1 = FOPEN(在Details.txt,R);
FP2 =的fopen(copydetails.txt,W); 如果(FP1 == NULL || FP2 == NULL)
{
的printf(读取文件错误\\ n);
出口(0);
}
的printf(文件打开正确的\\ n);
//第2步:从原始文件的文本//
而(与fgets(内容,strlen的(内容),FP1)!= NULL)
{
的fputs(内容,标准输出);
的strcpy(内容,newcontent);
}
的printf(%S,newcontent);
的printf(由原来的档案\\ n文本检索);//第3步:将文本复制到新的文件//
而(与fgets(内容,strlen的(内容),FP1)!= NULL)
{
fprintf中(FP2,newcontent);
}
的printf(创建的文件和文本复制到它);
//第4步:关闭这两个文件和程序结束//
FCLOSE(FP1);
FCLOSE(FP2);
返回0;
}
您需要修改:
而(与fgets(内容,strlen的(内容),FP1)!= NULL)
您需要的的sizeof
阵列内容
,而不是长度。
而(与fgets(内容的sizeof(内容),FP1)!= NULL)
就算你初始化内容
使用前的strlen()
将返回0,你会读出什么从文件
另外,如果你希望写你需要新的文件时重新读取输入文件或者 FCLOSE()
输入文件和 fopen()函数
,或退()
了。
I'm writing a basic program that copies a string from an existing text file and copies the text into a new text file. I'm almost there but I'm having a few small issues. First, I output the line of text to the screen after copying and it's giving me 3 random characters after the string. I want to know why this is happening. Also, the program is creating the new text file but not putting the string into the file.
Here's my code:
#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;
}
You need to change:
while(fgets(content, strlen(content), fp1) !=NULL)
you need the sizeof
the array content
, not the length.
while(fgets(content, sizeof(content), fp1) !=NULL)
Even if you had initialised content
before using it strlen()
would return 0 and you would have read nothing from the file.
Also, if you want to re-read the input file when writing the new file you need to either fclose()
the input file and fopen()
it or rewind()
it.
这篇关于复制从一个文本文件中的数据到另一个用C的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!