我现在很难解决这个问题...在我的一个复制文件的功能中,它总是在尝试从一个文件读取到另一个文件时崩溃。我也是初学者,对于我所犯的任何错误都很抱歉。
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);
}
答案 0 :(得分:0)
尝试更改行
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*)
采用打开的文件指针而不是字符串作为参数。