fopen() in C returns NULL even when file e

2020-04-28 03:12发布

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 ideas?

int main(int argc, char **argv)
{
    DIR *pdir = NULL;
    struct dirent *in_file;
    FILE *signature = NULL;
    pdir = opendir(argv[1]);

      if (pdir == NULL)
       {
        printf("could not open directory %s", argv[1]);
        return -1;
      }

    while (in_file = readdir(pdir))
    {
        if (strcmp(in_file->d_name, "YouTubeSign") == 0)
        {
        signature = fopen(in_file->d_name, "r");
        printf("opening youtubesign");
        break;
        }
    }

    if (signature == NULL){
        printf("could not open file ");
        return -1;
    }

标签: c fopen readdir
3条回答
家丑人穷心不美
2楼-- · 2020-04-28 03:26

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");
查看更多
我只想做你的唯一
3楼-- · 2020-04-28 03:27

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.

查看更多
何必那么认真
4楼-- · 2020-04-28 03:39

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.

查看更多
登录 后发表回答