I am trying to list all the files in a directory specified by the user. I want the user to input "dir <directory>", where <directory> is obviously the specified folder. Currently if I input something like "dir /home" the directory cant be found. However if I input something like "dir /home sdlgjhsdlgsdljg" it works... lol. As long as input a 3rd string to be tokenized it works. Not sure why it does this.
Code:
#include <dirent.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <errno.h>
int main( int argc, char * argv[] )
{
char *prompt = getcwd(NULL, 0);
char *cmd = NULL;
char *cmdCopy[100];
char * tokenPtr;
int bytes_read = 0;
size_t nbytes = 100;
int cmdCount = 0;
int i = 0;
pid_t pid;
int done = 0;
DIR *dp;
struct dirent *ep;
char ch;
while(!done)
{
//take input
while( bytes_read <= 1)
{
printf("[%s ~]$ " , prompt);
bytes_read = getline(&cmd, &nbytes, stdin);
}
//tokenize
tokenPtr = strtok(cmd, " \n");
while(tokenPtr != NULL)
{
cmdCopy[cmdCount] = tokenPtr;
++cmdCount;
tokenPtr = strtok(NULL, " ");
}
cmdCopy[cmdCount] = NULL;
//display cmdCopy[]
int l = 0;
for( l = 0; l <= cmdCount; ++l )
{
printf("cmdCopy[%d] = %s\n", l, cmdCopy[l]);
}
//determine if first arg is dir
if( strcmp(cmdCopy[0], "dir") == 0) //dir
{
//make sure a second arg was supplied
if( cmdCopy[1] == NULL )
{
printf("<Direcotry not specified.\n");
}
else
{
//display contents
dp = opendir( cmdCopy[1] );
printf("Getting files in cwd\n");
if( dp != NULL )
{
while( ep = readdir( dp ))
puts ( ep->d_name);
(void) closedir(dp);
}
else
perror("Couldnt open directory");
}
}
done = 1;
}
return 1;
}