Thread: List all files except "." and ".."

  1. #1
    Registered User
    Join Date
    Jul 2009
    Posts
    1

    List all files except "." and ".."

    So I am trying to list all the files in a directory except for "." and "..", it seems simple enough. So I try this test program:

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <dirent.h>
    
    int main(int argc, char ** argv){
    	DIR *dp;
    	struct dirent *ep;
    	dp = opendir (".");
    	if (dp != 0) {
    		while (ep = readdir(dp)) {
    			if (ep->d_name == ".." || ep->d_name == ".") continue;
    			printf("%s\n", ep->d_name);
    		}
    		(void) closedir (dp);
    	}
    }
    But it doesn't work! ".." and "." are still listed!

    What is wrong with my program?

  2. #2
    Dr Dipshi++ mike_g's Avatar
    Join Date
    Oct 2006
    Location
    On me hyperplane
    Posts
    1,218
    You can't do string comparisons like that. Lookup strcmp that will do what you want.

  3. #3
    Registered User
    Join Date
    Oct 2008
    Location
    TX
    Posts
    2,059
    Use strcmp() for comparing strings not "==".

Popular pages Recent additions subscribe to a feed