首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >C语言编程。尝试读写时程序崩溃

C语言编程。尝试读写时程序崩溃
EN

Stack Overflow用户
提问于 2017-05-30 03:04:39
回答 1查看 65关注 0票数 0

我现在很难弄清楚这个问题...在我的一个复制文件的函数中,当尝试从一个文件读取到另一个文件时,它总是崩溃。另外,我是一个初学者,所以我为我所做的任何错误感到抱歉。

代码语言:javascript
运行
复制
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;
}

编辑:将这两个分开后,它现在可以工作了:

代码语言:javascript
运行
复制
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);
}
EN

回答 1

Stack Overflow用户

发布于 2017-05-30 03:24:52

尝试更改行

代码语言:javascript
运行
复制
if (((fr_source = fopen(path_current, "r")) && (fw_target = fopen(path_new, "w"))) == NULL) {

代码语言:javascript
运行
复制
if (((fr_source = fopen(path_current, "r")) == NULL) || ((fw_target = fopen(path_new, "w")) == NULL)) {

类似地,

代码语言:javascript
运行
复制
if ((fclose(path_current)) && (fclose(path_new)) == EOF) {

应该是

代码语言:javascript
运行
复制
if ((fclose(fr_source) == EOF) || (fclose(fw_target) == EOF)) {

使用(ptr1 && ptr2) == NULL格式令人困惑,并在许多编译器上抛出警告(当然,如果您使用gcc -Wall -pedantic,我就是这样做的)。

此外,int fclose(FILE*)以打开的文件指针而不是字符串作为其参数。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/44249038

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档