Accessing Directories in C

前端 未结 3 2067
萌比男神i
萌比男神i 2020-12-11 12:55

The program is to open a directory and to display the name of the files... i.e if there is a file..it should say FILE....else DIRECTORY.. but the program displays all the f

3条回答
  •  暖寄归人
    2020-12-11 13:41

    One problem is that a directory is also a type of file, and can be normally fopen()ed. You want to call lstat() on each file to check whether it is a directory. Like this:

    struct stat st;
    lstat(dent->d_name, &st);
    if(S_ISDIR(st.st_mode))
       printf("\t DIRECTORY\n");
    else
       printf("\t FILE\n");
    

    But this error should lead to all entries being displayed as files. Do you have read permissions for the files in this directory? What is the value of errno after the fopen() call?

提交回复
热议问题