我现在很难弄清楚这个问题...在我的一个复制文件的函数中,当尝试从一个文件读取到另一个文件时,它总是崩溃。另外,我是一个初学者,所以我为我所做的任何错误感到抱歉。
int file_copy(void)
{
char path_new[MAX_PATH];
file_load();
printf("New name: ");
scanf("%s", path_new); // <---- Crash right after entering a new path
FILE *fr_source, *fw_target;
if (((fr_source = fopen(path_current, "r")) && (fw_target = fopen(path_new, "w"))) == NULL) {
printf("Error while opening one of these files");
exit(6);
}
int c;
while((c = getc(fr_source)) != EOF) {
fputc(c, fw_target);
}
printf("File copied successfully.\n");
if ((fclose(path_current)) && (fclose(path_new)) == EOF) {
printf("Error while closing one of these files");
exit(7);
}
return 0;
}
int file_load(void)
{
printf("Path to current file: ");
scanf("%s", path_current);
if (file_access(path_current) != 0)
exit(2);
return 0;
}
int file_access(char path[])
{
if ((access(path, F_OK)) != 0) {
printf("ERROR = %s.\n", strerror(errno));
exit(1);
}
return 0;
}编辑:将这两个分开后,它现在可以工作了:
if ((fr_source = fopen(path_current, "r")) == NULL) {
printf("Error while opening one of these files");
exit(6);
}
if ((fw_target = fopen(path_new, "w")) == NULL) {
printf("Error while opening '%s'\n", path_new);
exit(6);
}发布于 2017-05-30 03:24:52
尝试更改行
if (((fr_source = fopen(path_current, "r")) && (fw_target = fopen(path_new, "w"))) == NULL) {至
if (((fr_source = fopen(path_current, "r")) == NULL) || ((fw_target = fopen(path_new, "w")) == NULL)) {类似地,
if ((fclose(path_current)) && (fclose(path_new)) == EOF) {应该是
if ((fclose(fr_source) == EOF) || (fclose(fw_target) == EOF)) {使用(ptr1 && ptr2) == NULL格式令人困惑,并在许多编译器上抛出警告(当然,如果您使用gcc -Wall -pedantic,我就是这样做的)。
此外,int fclose(FILE*)以打开的文件指针而不是字符串作为其参数。
https://stackoverflow.com/questions/44249038
复制相似问题