saving and transfering data from one text file to another

67 views Asked by At

Having problems with transferring a data from one text file to another. My idea is to transfer it per character but it seems to not be working. I have added these codes at the beginning

FILE *addressPtr;
FILE *ressPtr;   

and

addressPtr = fopen("temporary.txt","w");

These set of codes are in a switch condition

fclose(addressPtr);
addressPtr = fopen("temporary.txt","r");
while((filechar = fgetc(addressPtr)) != EOF){
    fclose(addressPtr);
    ressPtr = fopen("Address Book.txt","a");
    fprintf(ressPtr,"%c",filechar);
    fclose(ressPtr);
    addressPtr = fopen("temporary.txt","r");
}
printf("The file has been successfully saved!!");

I just learned about these file operations and dont really know what went wrong

If I open my Address Book.txt file it will only display the first character of my temporary.txt but continuously (never-ending).

1

There are 1 answers

0
Ashis Kumar Sahoo On

You need to open the files in binary mode.

addressPtr = fopen("temporary.txt","wb");

also write in binary mode using "rb" to open the file.

I'm not sure why you're using fopen inside a loop. But if you want to copy a file then this is some working code I've tested:

#include<stdio.h>

int main()
{
    FILE *addressPtr;
    FILE *ressPtr;
    char filechar = '\0';

    addressPtr = fopen("D:\\test\\source.jpg","rb");
    ressPtr = fopen("D:\\test\\dest.jpg","wb");

    while(!feof(addressPtr))
    {
        filechar = fgetc(addressPtr);
        fprintf(ressPtr,"%c",filechar);
    }
    fclose(addressPtr);
    fclose(ressPtr);
    printf("The file has been successfully saved!!");

}

This essentially copies a file called source.jpg to another file called dest.jpg.

Hope you got your answer.