c - 交换两个文件的内容

标签 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();

}

最佳答案

例如

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

    rename("E:/FileText.txt", "tempname");
    rename("E:/CombineContents.txt","E:/FileText.txt");
    rename("tempname", "E:/CombineContents.txt");
    //perror("rename");

关于c - 交换两个文件的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20755195/

相关文章:

字符数组打印垃圾,除非我增加数组大小

c - 与 sscanf 一起使用的格式说明符 %n 不返回字符数

c++ - 使用 C++ 检索网站数据

c# - 我可以使用哪些工具在 Visual Studio 2010 Professional Edition 中分析 .Net 应用程序

asp.net - VS2010中切换到aspx代码的热键

asp.net-mvc - 为 MVC 应用程序创建帮助和手册

c - 删除单链表C中字符串中出现的子串

c++ - 给定一个填充 unsigned char** 的 C 函数,如何在没有中间拷贝的情况下用数据填充 std::vector

c++ - QT 5 64 位适用于 Windows 和 VS2010

silverlight - 使用自定义URL参数启动VS2010 Silverlight调试 session