Thread: opendir() help

  1. #1
    Registered User
    Join Date
    Dec 2011

    opendir() help


    I am currently working on code that asks the user to input a directory and then it displays all the files, file sizes... about that directory, the only part i am struggling with is getting it to read from the directory that the user inputs. When the user inputs the directory they want (for example /home/<username>) it stores this directory in a char.

    Here is my code

    #include <stdio.h>
    #include <dirent.h>
    #include <sys/stat.h>
    #include <string.h>
    #include <sys/types.h>
    #include <stdlib.h>
    #include <fcntl.h>
    #include <unistd.h>
    	int main(int argc, char *argv[]){
    	const int MAXPATHLEN = 1024;
    	char cwd[MAXPATHLEN];
    	char str[100];
    	printf("Enter Directory...");
    	DIR *currentDirectory;
    	struct dirent *fileEntry;
    	struct stat buffer;
    	char *filename;
    	currentDirectory = opendir(str);
    		if( currentDirectory != NULL ) {
    				while( ( fileEntry = readdir( currentDirectory ) ) != NULL ) {
    					char *filename = fileEntry->d_name;
    					//int status;
    					stat(filename, &buffer);	
    					int size = buffer.st_size;
    					getcwd(cwd, MAXPATHLEN);
    					printf( "%s\t%s\t%d bytes\n", fileEntry->d_name,cwd,buffer.st_size);
    			closedir( currentDirectory );
    	return 0;
    I have read all the man pages but am left confused.

    This is the line i believe to be the issue
    currentDirectory = opendir(str);
    The code does compile without errors.



  2. #2
    Registered User
    Join Date
    Sep 2007
    Although you check whether opendir() returns NULL, you don't actually do anything if it does. At the very least, you could look and see what the problem is. Likely it's the fact that fgets() stores a '\n' at the end of the buffer (if it read one), and your directory does not end in a '\n'. You'll want to strip it off.

    In the future, please be specific about what the problem is. I had to guess, because you never said what goes wrong.

  3. #3
    Registered User
    Join Date
    Dec 2011
    THs issue was that it wouldnt output anything, sorry for the lack of info. I will try what you have suggested now.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. opendir problem
    By raczzoli in forum C Programming
    Replies: 10
    Last Post: 07-24-2011, 04:24 PM
  2. opendir fail
    By eyal_lesh in forum C Programming
    Replies: 2
    Last Post: 06-07-2011, 02:32 AM
  3. opendir failure
    By MK27 in forum C Programming
    Replies: 5
    Last Post: 07-10-2008, 03:47 PM
  4. php: glob() vs opendir() and friends
    By MisterSako in forum Tech Board
    Replies: 1
    Last Post: 03-16-2006, 01:42 AM
  5. opendir(), readdir()
    By BigDaddyDrew in forum C++ Programming
    Replies: 1
    Last Post: 03-24-2003, 12:22 PM

Tags for this Thread