3

I have the below code, I am trying to interchange contents of two files. I am able to interchange two files by using the below code. Is there any way to interchange two files other than the following method.

# include <stdio.h>
# include <conio.h>
# include <process.h>

void main()
{
    FILE *f1,*f2,*f3;
    char ch;
    f1=fopen("E:/FileText.txt","r");
    f2=fopen("E:/CombineContents.txt","r");
    f3=fopen("E:/FileCopy.txt","w");
    if(f1==NULL)
    {
        printf("Cannot open file");
        getche();
        exit(1);
    }
    if(f2==NULL)
    {
        printf("Cannot open file");
        getche();
        exit(1);
    }
    if(f3==NULL)
    {
        printf("Cannot open file");
        getche();
        exit(1);
    }


    printf("\nCopying contents from f2 to f3:");
    while(!feof(f2))
    {
        fputc(fgetc(f2),f3);
    }
    fcloseall();
    printf("\nContents copied from f2 to f3 are :");
    f3=fopen("E:/FileCopy.txt","r");
    while((ch=fgetc(f3))!=EOF)
    {
        printf("%c",ch);
    }
    fclose(f3); 
    getche();


    printf("\nCopying contents from f1 to f2:");
    f1=fopen("E:/FileText.txt","r");
    f2=fopen("E:/CombineContents.txt","w");
    if(f1==NULL || f2==NULL)
    {
        printf("Cannot open file");
        getche();
        exit(1);
    }
    while(!feof(f1))
    {
        fputc(fgetc(f1),f2);
    }
    fcloseall();
    printf("\n Contents copied from f1 to f2 are :");
    f2=fopen("E:/CombineContents.txt","r");
    while((ch=fgetc(f2))!=EOF)
    {
        printf("%c",ch);
    }
    fclose(f2);
    getche();


    printf("\nCopying contents from f3 to f1:");
    f3=fopen("E:/FileCopy.txt","r");
    f1=fopen("E:/FileText.txt","w");
    if(f1==NULL || f3==NULL)
    {
        printf("Cannot open file");
        getche();
        exit(1);
    }
    while(!feof(f3))
    {
        fputc(fgetc(f3),f1);
    }
    fcloseall();
    printf("\nContents copied are:");
    f1=fopen("E:/FileText.txt","r");
    while((ch=fgetc(f1))!=EOF)
    {
        printf("%c",ch);
    }
    fclose(f1);
    getche();

}
jessehouwing
  • 106,458
  • 22
  • 256
  • 341
user3027039
  • 221
  • 3
  • 7
  • 20
  • 7
    Yes, just inter change the file names... –  Dec 24 '13 at 05:15
  • What about: 1) `MoveFile(fileA, tmp)`, 2) `MoveFile(fileB, fileA)`, 3) `MoveFile(tmp, FileA)`? PS: What's this ancient "conio.h" stuff??? Are you running on 16-bit MS-DOS? – paulsm4 Dec 24 '13 at 05:17
  • Why do you want to interchange them? As posted now, your question is off-topic because it is not aiming anywhere, solicits discussion. Please take the time to make it clear, useful and otherwise on-topic, see [help/on-topic]. – Palec Dec 24 '13 at 05:30

1 Answers1

2

E.g

    //char *tempname;
    //tempname = tmpnam(NULL);

    rename("E:/FileText.txt", "tempname");
    rename("E:/CombineContents.txt","E:/FileText.txt");
    rename("tempname", "E:/CombineContents.txt");
    //perror("rename");
BLUEPIXY
  • 39,699
  • 7
  • 33
  • 70