繁体   English   中英

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

[英]How to copy content of one file to another in 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文件,但两者均无效)

我建议进行以下更改。

建议1

采用

int a;

代替

char a;

根据您平台上的char类型是签名还是未签名,

a = fgetc(fp1);

如果achar类型a则可能会出现问题,因为fgetc返回一个int

建议2

do-while循环是有缺陷的。 即使使用当前设置fputc(a, fp2)即使a = EOF ,您最终仍将调用fputc(a, fp2) 更改为:

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

我尝试了您的代码,它可以工作,但是它会向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

该功能将第一文件的内容复制到第二文件。 如果第二个文件存在-将覆盖它,否则-将创建它并将第一个文件的内容写入其中。 此函数的关键是函数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;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM