交换两个文件的内容

时间:2013-12-24 05:12:21

标签: c visual-studio-2010

我有以下代码,我正在尝试交换两个文件的内容。 我可以使用下面的代码交换两个文件。 除了以下方法之外,有没有办法交换两个文件。

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

}

1 个答案:

答案 0 :(得分:1)

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