-
opendir() help
Hi.
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
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...");
fgets(str,100,stdin);
DIR *currentDirectory;
struct dirent *fileEntry;
struct stat buffer;
char *filename;
currentDirectory = opendir(str);
printf("Name\tInode\tSize\n");
if( currentDirectory != NULL ) {
while( ( fileEntry = readdir( currentDirectory ) ) != NULL ) {
char *filename = fileEntry->d_name;
//int status;
//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
Code:
currentDirectory = opendir(str);
The code does compile without errors.
Thanks
C
-
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.
-
THs issue was that it wouldnt output anything, sorry for the lack of info. I will try what you have suggested now.