Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I am having a bit of trouble creating a C program that reads the current directory, prints the file path, and contents.

For each file found in the directory the contents should be printed based on whether they are a directory, a file, or executable.

I have the main components working just unsure how to sort the files output after using the opendir() / closedir() command

eg. end output:

/home/documents/folder1
File:       help.txt
File:       me.txt
Executable: plz
File:       thankyou.c  

Current code:

struct dirent *de;  // Pointer for directory entry

// opendir() returns a pointer of DIR type.
DIR *dir = opendir(".");//opens current direcotry

if (dir == NULL)  // opendir returns NULL if couldn't open directory
{
    printf("ERROR: Could not open current directory" );
    return 1;
}

// for readdir()
while ((de = readdir(dir)) != NULL){

      //if (Executable){}
      //else if (File){}
      //else if (Directory){}
        printf("%s
", de->d_name);
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
321 views
Welcome To Ask or Share your Answers For Others

1 Answer

You can use d_type from struct dirent to check the type of the file and access with X_OK to check whether file is executable.

#include <stdio.h>
#include <dirent.h>
#include <string.h>
#include <unistd.h>

int main()
{
    DIR *dir;
    struct dirent *dp;
    char * file_name;
    dir = opendir(".");
    while ((dp=readdir(dir)) != NULL) {
        if ( !strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..") )
        {
            // do nothing (straight logic)
        } else {
            file_name = dp->d_name; // use it
            if (access(file_name, X_OK) != -1) {
             printf("executable:");
            }
            else if (dp->d_type == DT_DIR)
            {
               printf("directory:");
            }
            else if(dp->d_type == DT_REG)
            {
               printf("file:");
            }
            printf("     "%s"
",file_name);
        }
    }
    closedir(dir);
    return 0;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...