交换两个文件的内容

3

我有以下代码,我想交换两个文件的内容。 我能够使用下面的代码交换两个文件。 除了以下方法,是否有其他交换两个文件的方法。

# 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();

}

7
好的,只需要交换文件名即可。 - user1814023
关于:1)MoveFile(fileA, tmp),2)MoveFile(fileB, fileA),3)MoveFile(tmp, FileA)?另外,这个古老的“conio.h”是什么东西?你是在16位MS-DOS上运行吗? - paulsm4
你为什么想要交换它们?按照现在的发布方式,你的问题是不相关的,因为它没有明确的目标,征求讨论。请花时间使其清晰、有用和符合主题,参见[帮助/主题]。 - Palec
1个回答

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");

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接