fopen() in C returns NULL even when file exists (is returned by readdir())

后端 未结 3 1356
囚心锁ツ
囚心锁ツ 2021-01-23 17:43

I am trying to open a directory, and then open a file named \"YouTubeSign\", directory opens fine, but for some reason fopen() on the file fails even if the file exists; any ide

相关标签:
3条回答
  • 2021-01-23 18:04

    The problem is that the file-name you get from readdir does not include the base path provided to opendir.

    You have to create the full path using the base path, the path separator and the file-name.

    0 讨论(0)
  • 2021-01-23 18:12

    You have to pass an absolute file name when you use fopen(), composed with the directory name and file base name, e.g.:

    char abs_path[PATH_MAX];
    // ...
    snprintf(abs_path, PATH_MAX, "%s/%s", argv[1], in_file->d_name);
    signature = fopen(abs_path, "r");
    
    0 讨论(0)
  • 2021-01-23 18:19

    The problem is that it will work from the command line when you're testing this code. There's nothing technically missing here. You need to make sure that the process is using the correct working directory.

    0 讨论(0)
提交回复
热议问题