Madara Uchiha
Madara Uchiha

Reputation: 21

File Operation in C

Recently, I've started working on File Operations in C, and I was successfully able to copy the contents of one file to another.

I went a step ahead to read the content of a file from the start of the file and then to write the same content at the end of the same file. (Similar to appending). But I'm not able to do so.

Here is the code that I've written. Can anyone suggest, what is the mistake I've done here?

#include <stdio.h>

int main(int argc, char **argv)
{
int size = 0, index = 0;

char byte = 0; 

FILE *fp_read, *fp_write;

if ((fp_read = fopen(argv[1], "r+")) == NULL)
{
    printf("Unable to Open File %s\n", argv[1]);
}

fp_write = fp_read;

fseek(fp_write, 0, SEEK_END);

size = ftell(fp_write);

printf("The Size of the file %s:\t%d\n", argv[1], size);

for (index = 0; index < size; index++)
{
    if (fread(&byte, 1, 1, fp_read) != 1)
    {
        printf("Unable to Read from the file at Location:\t%d\n", index);
    }

    if (fwrite(&byte, 1, 1, fp_write) != 1)
    {
        printf("Unable to Write to the file at Location:\t%d\n", index);
    }
}

if (fclose(fp_read))
{
    printf("Unsuccessful in Closed the File\n");
}

return 0;
}

Regards,

Naruto Uzumaki

Upvotes: 0

Views: 256

Answers (2)

Dan
Dan

Reputation: 393

Similar to the answer prior, you are treating both pointers as if they are referencing different FILE streams. When you perform the fseek function, you are changing where the FILE pointer is located. As a check, try running ftell on both fp_read and fp_write and printing them out to determine if they are at different spots.

Edit: As mentioned by the comment, you could open a second stream for the fp_write variable as follows to append.

fp_write = fopen("somefile", "a");

Upvotes: 1

user1084944
user1084944

Reputation:

Your mistake is treating fp_read and fp_write as if they weren't pointing to the same FILE object.

Upvotes: 2

Related Questions