Question: I'm not sure if C can do this, but I'm hoping that I can make a program that will look into a directory, and print out all of the contents of the directory along with the file size of each file. As in I wanted it to look like this (possibly):

> 
> filename.txt -- 300 bytes
> 
> 
> filename2.txt -- 400 bytes
> 
> 
> filename3.txt -- 500 bytes
> 
> 
> 

And so on.

So far, I created a program that can open a file, and it will print the bytes, but it does not read the entire directory, and I have to be specific with which file I want to read.. (which is not what I want).

Here is what I have so far:

```
#include <stdio.h>

int main(){
    FILE *fp; // file pointer
    long fileSize;
    int size;

    // opens specified file and reads
    fp = fopen( "importantcommands.txt", "rw" );

    if( fp == NULL ){
        printf( "Opening file error\n" );
        return 0;
    }

    // uses fileLength function and prints here
    size = fileLength(fp);
    printf( "\n Size of file: %d bytes", size );

    fclose(fp);

    return 0;
}

int fileLength( FILE *f ){
    int pos;
    int end;

    // seeks the beginning of the file to the end and counts
    // it and returns into variable end
    pos = ftell(f);
    fseek (f, 0, SEEK_END);
    end = ftell(f);
    fseek (f, pos, SEEK_SET);

    return end;
}

```

Please help.

Answer: 
C can certainly do it - the [`ls(1)`](http://www.manpagez.com/man/1/ls/) command can, for example, and it's written in C.

To iterate over a directory, you can use the [`opendir(3)`](http://www.manpagez.com/man/3/opendir/) and [`readdir(3)`](http://www.manpagez.com/man/3/readdir/) functions. It's probably easier to just let the shell do it for you, though.

As far as getting the filename, you can just take it as a command line parameter by defining main as:

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

```

Command line parameters will begin at `argv[1]`.
There are little things need to be taken care for the given examples (under Linux or other UNIX).

1. You properly only want to print out the file name and size of a regular file only. Use `S_ISREG()` to test the `st_mode` field
2. If you want to recursively print out all files under sub directories also, you then need to use `S_ISDIR()` to test for direcotry and be carefull of special directory `'.' and '..'`.