首页 > 解决方案 > 为什么这个函数不复制输入文件?

问题描述

我刚刚开始使用文件 I/O,并且正在尝试构建一个函数,该函数将简单地将文件复制到目标。

该程序可以编译,但是会创建一个空文件并且不会复制任何内容。有什么建议吗?

#include <stdio.h>

int copy_file(char FileSource[], char FileDestination[]) {
    char content;

    FILE *inputf = fopen(FileSource, "r");
    FILE *outputf = fopen(FileDestination, "w");

    if (inputf == NULL)
        ;
    printf("Error: File could not be read \n");
    return;

    while ((content = getc(inputf)) != EOF) putc(content, inputf);

    fclose(outputf);
    fclose(inputf);
    printf("Your file was successfully copied");

    return 0;
}


int main() {
    char inputname[100];
    char outputname[100];

    printf("Please enter input file name: \n");
    scanf("%s", &inputname);
    printf("Please write output file name: \n");
    scanf("%s", &outputname);

    copy_file(inputname, outputname);

    return 0;
}

标签: cfile-io

解决方案


您提到的代码中几乎没有错误。下面这两个声明

scanf("%s", &inputname);
scanf("%s", &outputname);

错误的inputnameoutputname是 char 数组和数组名本身的地址,所以你不需要&inputnamescanf(). 例如

scanf("%s",inputname);
scanf("%s",outputname);

同样,在声明;的末尾if也没有像您预期的那样服务于正确的目的。

这个

if(inputf == NULL);

应该

if(inputf == NULL){ 
     /*error handling */ 
}

正如其他人所指出的,getc()返回intnot char。从手册页getc()

int getc(FILE *stream);

和这个

 putc(content, inputf);

改成

putc(content, outputf); /* write the data into outputf */

推荐阅读