Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
316 views
in Technique[技术] by (71.8m points)

c - Reading current directory, printing results based on file attributes

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

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

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...