I'm trying to append the contents of a file myfile.txt to the end of a second file myfile2.txt in c. I can copy the contents, but I can't find a way to append. Here's my code:
FILE *pFile;
FILE *pFile2;
char buffer[256];
pFile=fopen("myfile.txt", "r");
pFile2=fopen("myfile2.txt", r+);
if(pFile==NULL) {
perror("Error opening file.");
}
else {
while(!feof(pFile)) {
if(fgets(buffer, 100, pFile) != NULL) {
fseek(pFile2, -100, SEEK_END);
fprintf(pFile2, buffer);
}
}
fclose(pFile);
fclose(pFile2);
I don't think I'm using fseek correctly, but what I'm trying to do is call fseek to put the pointer at the end of the file, then write at the location of that pointer, instead of at the beginning of the file. Is this the right approach?
fseek
idea ought to work, but since you useSEEK_END
the 'pointer' is already at the very end-- and then you go "back" 100 characters. Use0
for the offset and it ought to work. (Minor: you check if your reading file can open, but not your writing file. Check both.) – Starinsky