Skip to content

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

Open
@cirosantilli

Description

@cirosantilli

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 =)

Metadata

Metadata

Assignees

No one assigned

    Labels

    stack-exchangePosts that were deleted by in that stupid website that allows post deletion.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions