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: 
See `opendir() / fdopendir()` and `readdir()` if you are using linux in `dirent.h`
[man page](http://linux.die.net/man/3/opendir)

Simple example from a : [SO Post](https://stackoverflow.com/questions/612097/how-can-i-get-a-list-of-files-in-a-directory-using-c-or-c)

```
DIR *dir;  
struct dirent *ent;
if ((dir = opendir ("c:\\src\\")) != NULL) {
  /* print all the files and directories within directory */
  while ((ent = readdir (dir)) != NULL) {
     printf ("%s\n", ent->d_name);
  }
  closedir (dir);
} 
else {
  /* could not open directory */
  perror ("Could not open directory");
  return EXIT_FAILURE;
}   

```

Also You can use the [fstat()](http://linux.die.net/man/2/fstat) system call which can fill in the `struct stat` for any file you want. From that `stat` you can access that file's size.  

Please use the `man` pages to help you out. (Almost) Everything related to Linux is insanely well documented.
To get the list of files in a directory look for "libc opendir". To get the size of a file without opening it you can use fstat.