help with printing file names in current directory for C

How do I print all the file names in current directory in C?

Well, dirent() is a touchy little bit of code, so read the man page carefully else you SEGV. You can also popen( "ls -1", "r" ) but that is cheating.

this code seems to do the trick but can you explain how it works (like what each line means)?

        DIR *d;
        struct dirent *dir;
        d = opendir(".");
        if (d) {
            while ((dir = readdir(d)) != NULL) {
                printf("%s\n", dir->d_name);
            }
            closedir(d);
        }

Pull down the stack pointer to create space for a DIR pointer called d and a struct dirent pointer called dir. Call opendir to get a starting dirent for ".". If it is not null (see man opendir for returns and errno's), then call readdir() on d to put a struct dirent * into dir, which is a static storage inside readdir and probably not thread-safe. If the pointer returned is not null, dereference it to a char* of its d_name, print that and a new line to the stdout buffered FILE* and loop back to call readdir(), else call closedir() on d to close the FD open to read the directory.

Directories contain just entry names and inode numbers. Directories grow but never shrink, as deletions are just nulled out. A flat file can have its inode number in man directories, and there is a link count on the inode so it can tell if it is completely deleted. You can see this on ls -l.

Can anyone explain stat, i want to use it to print the filenames of all files in current directory.

stat()

not working...