c - 为什么这个函数不复制输入文件?
问题描述
我刚刚开始使用文件 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;
}
解决方案
您提到的代码中几乎没有错误。下面这两个声明
scanf("%s", &inputname);
scanf("%s", &outputname);
错误的inputname
和outputname
是 char 数组和数组名本身的地址,所以你不需要&inputname
给scanf()
. 例如
scanf("%s",inputname);
scanf("%s",outputname);
同样,在声明;
的末尾if
也没有像您预期的那样服务于正确的目的。
这个
if(inputf == NULL);
应该
if(inputf == NULL){
/*error handling */
}
正如其他人所指出的,getc()
返回int
not char
。从手册页getc()
int getc(FILE *stream);
和这个
putc(content, inputf);
改成
putc(content, outputf); /* write the data into outputf */
推荐阅读
- google-dfp - Google Ad Manager - 同一订单项在屏幕上投放所有广告单元,即使它没有足够的广告素材
- android - 用于屏幕指纹的 Android API
- internationalization - i18next-browser-languageDetector 路径不起作用
- python - 使用 Pandas 动态创建数据框
- python - Cython 中的“仅限 C”类
- maven - 使用配置文件创建分解的 JAR 文件
- git - 通过命令行从 Azure Devops 下载应用程序
- javascript - 从 Blazor 使用 JSInterop 读取输入文件
- python-3.x - Python 代码中的错误:应用 style_function 方法更改颜色后,编译器给我一个错误
- azure - Azure cosmos DB 文档大小约为 30KB 时速度慢