如何在C中将一个文件的内容复制到另一个文件

时间:2015-10-28 20:01:18

标签: c

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

void main() {
FILE *fp1, *fp2;
char a;

fp1 = fopen("input.txt", "r");
if (fp1 == NULL) {
  puts("cannot open this file");
  exit(0);
}

fp2 = fopen("output.txt", "w");
if (fp2 == NULL) {
  puts("Not able to open this file");
  fclose(fp1);
  exit(0);
}

do {
  a = fgetc(fp1);
  fputc(a, fp2);
} while (a != EOF);

fclose(fp1);
fclose(fp2);
getch();
}

我创建文件input.txt和output.txt,在运行程序后,我没有看到文本被复制。 (我从cmd创建.txt文件,也直接从记事本创建。但两者都没有工作)

3 个答案:

答案 0 :(得分:3)

我建议进行以下更改。

建议1

使用

int a;

而不是

char a;

取决于您的平台上char的类型是已签名还是未签名,

a = fgetc(fp1);
如果a的类型为char,那么

可能会出现问题,因为fgetc会返回int

建议2

do-while循环存在缺陷。您最终会使用当前设置为fputc(a, fp2)调用a = EOF。将其更改为:

while ( (a = fgetc(fp1)) != EOF )
{
   fputc(a, fp2);
}

答案 1 :(得分:1)

我尝试了你的代码并且它可以工作,但是它为output.txt添加了垃圾值。因此你必须将do-while循环更改为while循环来解决此问题。

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

void main() {
    FILE *fp1, *fp2;
    int a;

    fp1 = fopen("input.txt", "r");
    if (fp1 == NULL) {
      puts("cannot open this file");
      exit(0);
    }

    fp2 = fopen("output.txt", "w");
    if (fp2 == NULL) {
      puts("Not able to open this file");
      fclose(fp1);
      exit(0);
    }
    while( (a = fgetc(fp1)) != EOF )
    {
      fputc(a, fp2);
    }

    fclose(fp1);
    fclose(fp2);
}

您还可以使用getcputc代替fgetcfputc

答案 2 :(得分:0)

此功能将第一个文件的内容复制到第二个文件。如果第二个文件存在 - 将覆盖它,否则 - 将创建它并将第一个文件的内容写入其中。此功能的关键是函数 fputc()http://www.cplusplus.com/reference/cstdio/fputc/)。

解决方案

#include <stdio.h>

/**
 * Copy content from one file to other file.
 */
int
copy_file(char path_to_read_file[], char path_to_write_file[])
{
    char chr;
    FILE *stream_for_write, *stream_for_read;

    if ((stream_for_write = fopen(path_to_write_file, "w")) == NULL) {
        fprintf(stderr, "%s: %s\n", "Impossible to create a file", path_to_write_file);
        return -1;
    }

    if ((stream_for_read = fopen(path_to_read_file, "r")) == NULL) {
        fprintf(stderr, "%s: %s\n", "Impossible to read a file", path_to_read_file);
        return -1;
    }

    while ((chr = fgetc(stream_for_read)) != EOF)
        fputc(chr, stream_for_write);

    fclose(stream_for_write);
    fclose(stream_for_read);

    return 0;
}

<强>用法:

int
main(int argc, char *argv[])
{
    copy_file("file1", "file2");
    return 0;
}
相关问题