除非输入字符串,否则fopen无法打开存在的文件

时间:2016-07-13 20:31:45

标签: c file-io

我正在尝试通过解析zenity --file-selection的输出来打开文件,但是我遇到了一个问题,即文件永远不会打开,我从errno得到Error: 2 (No such file or directory)。但是,如果我只是简单地复制printf("%s", file_to_open);的输出并将其粘贴到引号之间并将其传递给fopen,那么即使传递file_to_open本身也无效,它仍按预期工作。我在linux上运行所以我不应该对'\'有问题。

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>

char * select_file(void)
{
    static char path[1024];
    memset(path, 0, sizeof(path));

    FILE *fp = popen("zenity --file-selection --title=\"Choose Gameboy Rom\"", "r");

    if(fp == NULL)
    {
        printf("Failed to run command, make sure you have zenity installed!\n" );
        exit(EXIT_FAILURE);
    }

    fgets(path, sizeof(path), fp);
    pclose(fp);

    return path;
}

int main(void)
{
    FILE * fp;

    char file_to_open[1024];
    strcpy(file_to_open, select_file());
    printf("%s", file_to_open);

    fp = fopen(file_to_open, "r");
    if(fp == NULL)
    {
        printf("Error: %d (%s)\n", errno, strerror(errno));
        exit(EXIT_FAILURE);
    }

    fclose(fp);
    return 0;
}

(我之前在programmers.stackexchange上发布了这个,我被告知要发布在这里)

1 个答案:

答案 0 :(得分:1)

您需要从path的末尾删除换行符。

fgets(path, sizeof(path), fp);
size_t lastpos = strlen(path) - 1;
if (path[lastpos] == '\n') {
    path[lastpos] = 0;
}