Guido
Guido

Reputation: 2634

Reading a directory file in C

I'm trying to write a small program to show me the internal representation of a directory in linux (debian, specifically). The idea was a small C program using open(".", O_RDONLY), but this seems to give no output. The program is the following:

#include <stdio.h>
#include <fcntl.h>

int main(int argc, char** argv)
{
        int fd = open(argv[1],O_RDONLY,0 );
        char buf;

        printf("%i\n",fd);

        while(read(fd, &buf, 1) > 0)

                printf("%x ", buf);


        putchar('\n');
}

When I run it on regular files it works as expected, but on a directory such as ".", it gives no output. The value of fd is 3 (as expected) but the call to read returns -1.

Why isn't this working, and how could I achieve to read the internal representation?

Thanks!

Upvotes: 3

Views: 701

Answers (2)

smhx
smhx

Reputation: 2266

Directories are a filesystem specific representation and are part of the file system. On extfs, they are a table of string/inode pairs, unlike files which have blocks of data(that you read using your code above).

To read directory-specific information in C, you need to use dirent.h . Look at this page for more information http://pubs.opengroup.org/onlinepubs/7908799/xsh/dirent.h.html

On POSIX systems, the system call "stat" would give you all the information about an inode on the filesystem(file/directory/etc.)

Upvotes: 2

DarkDust
DarkDust

Reputation: 92335

For handling directories, you need to use opendir/readdir/closedir. Read the corresponding man pages for more infos.

To check whether a filename corresponds to a directory, you first need to call stat for the filename and check whether it's a directory (S_ISDIR(myStatStruc.st_mode)).

Upvotes: 7

Related Questions