Monado_III
Monado_III

Reputation: 13

fopen can't open file which exists, unless I input a string

I'm attempting to open a file by parsing the output from zenity --file-selection but I'm having a problem where the file will never open and I get Error: 2 (No such file or directory) from errno. However, if I simply copy the output from printf("%s", file_to_open); and paste it between quotes and pass it to fopen, it works as intended, even though passing file_to_open itself never works. I'm running on linux so I shouldn't be having a problem with '\'s.

#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;
}

(I posted this previously on programmers.stackexchange and I was told to post here)

Upvotes: 1

Views: 149

Answers (1)

Barmar
Barmar

Reputation: 780688

You need to remove the newline from the end of path.

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

Upvotes: 2

Related Questions