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]`.
This seems strangely similar to another question I saw recently. Anyway, here's my strangely similar answer (for Linux, not sure how it'll fare on Windows 7):

```
#include <stdio.h>
#include <dirent.h>
#include <sys/stat.h>

int main(int argc, char *argv[]) {
    struct stat file_stats;
    DIR *dirp;
    struct dirent* dent;

    dirp=opendir("."); // specify directory here: "." is the "current directory"
    do {
        dent = readdir(dirp);
        if (dent)
        {
            printf("%s  --  ", dent->d_name);
            if (!stat(dent->d_name, &file_stats))
            {
                printf("%u bytes\n", (unsigned int)file_stats.st_size);
            }
            else
            {
                printf("(stat() failed for this file)\n");
            }
        }
    } while (dent);
    closedir(dirp);
}

```