c - while 循环在文件复制中不起作用

标签 c loops

这里我尝试使用此代码将file1的内容复制到file2

#include<string.h>
#include<stdio.h>
#include<stdlib.h>

int main(){   
    FILE *fs,*ft;
    int ch;
    fs=fopen("C:\\Users\\BRAHMA JAISWAL\\Desktop\\a.txt","a+");
    if(fs==NULL){
        puts("Unable to open Source file");
        exit(1);
    }
    ft=fopen("C:\\Users\\BRAHMA JAISWAL\\Desktop\\b.txt","wb");
    if(ft==NULL)
    {
        puts("Unable to open TArget File");
       fclose(ft);
        exit(1);
    }

    puts("Enter anything which you want to write in source file:");
    int a;
    scanf("%d",&a);
    fprintf(fs,"%d",a);

    while(1)
    {
        ch=fgetc(fs);
        if(ch==EOF)break;
        fputc(ch,ft);
    }

    fclose(ft);
    fclose(fs);
    return 0;
}

它不起作用(file1的内容没有复制到file2)但是当我删除这部分代码时它就可以正常工作。

puts("Enter anything which you want to write in a source file:");
int a;
scanf("%d",&a);
fprintf(fs,"%d",a);

谁能说出问题所在吗?

最佳答案

您的fprintf(fs,"%d",a);实际上打印到您的源文件,而不是您的目标文件。

源文件可能应该以 r 模式打开,而不是 a+

关于c - while 循环在文件复制中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49210095/

相关文章:

c - 如何在 C 中不使用 playbin2 来使用 Gstreamer GUI?

c - 在C中的函数调用之间保存一个值

java - 等待更新

c - UDP 广播在 Linux 2.6.33.9 rt 上一段时间后中断

c++ - 字节顺序转换 C++

c++ - 如何使用 C++(g++) 编译器编译包含 C++ 关键字的 C 代码?

c - scanf 跳过一行

c++ - 在二维数组中查找最小值和最大值?

c - C中的循环是否保证按顺序执行?

python - 在 Python 中使用多个列表的 For 循环