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 used in this: _ fprintf(fp2, newcontent);_
and the signature of "fprintf" is int fprintf(FILE *stream, const char *format, ...); u miss the
This modified version of the program would do the job:
You need to change:
you need the
sizeof
the arraycontent
, not the length.Even if you had initialised
content
before using itstrlen()
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 andfopen()
it orrewind()
it.In strcpy the order of sec and dest is reversed
Also ideally I would not copy but rather concat to the buffer.