cirosantilli / cirosantilli.github.io

Source for: https://cirosantilli.com and https://ourbigbook.com/cirosantilli Build HTML with https://github.com/ourbigbook/ourbigbook with "npm install && npx ourbigbook ." You can use this issue tracker for anything you want to tell me, even if it is not related to the repo. I also use this repo as generic issue tracker for myself.
https://cirosantilli.com
Creative Commons Attribution Share Alike 4.0 International
42 stars 9 forks source link

program in c to list files and subdirectories for linux #59

Open cirosantilli opened 4 years ago

cirosantilli commented 4 years ago

You can do this in a POSIX compliant way with opendir, readdir and stat:

#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>

#include <dirent.h>
#include <errno.h>    
#include <sys/stat.h>
#include <unistd.h>

int main(int argc, char** argv)
{

    DIR* dp;
    struct dirent* entry;
    struct stat s;

    dp = opendir( "." );
    if ( dp == NULL )
    {
        perror( "opendir" );
    }
    else
    {
        printf( "opendir\n" );
        while( ( entry = readdir( dp ) ) != NULL)
        {
            stat( entry->d_name, &s );
            printf(
                "%s:\n  uid: %jd\n  gid: %jd\n",
                entry->d_name,
                (intmax_t)s.st_uid,
                (intmax_t)s.st_gid
            );
        }
    }

    return EXIT_SUCCESS;
}

And compile with:

gcc -Wall -std=c99 test.c

The cast to intmax_t is to make sure that we have a type large enough to represent uid.

You can see all the possible fields of stat at the POSIX docs. Structs are documented with the headers they are in, in this case stat.h.

Please take a look at the sources I cited in the comment before asking further questions. This is a basic question which you should be able to find on most books, and we at stackoverflow just don't want to duplicate answers too much. Don't be discouraged by downvotes =)