tokenaizer tokenaizer - 1 year ago 91
Linux Question

creating ls command in c

I'm trying to create ls command. First, the code is not working if I enter "ls", it's working only when I enter the full path. Second, it's not looping after the exevcp(). why?


int main(void){

char *line;
char *args[32];

memset(args, 0, sizeof(args));
while (1){
line = (char*)malloc(1024);
printf("$ ");
args[0] = strtok(line, " ");
args[1] = strtok(NULL, " ");

execvp(args[0], args);

Answer Source

It's not looping since execve() never returns. Also, this seems to be a very strange way to implement ls: you should try to open a directory and read its contents (the list of files), not run another command, I would expect.

Look into the opendir() and readdir() functions, that's one way of actually implementing ls.

And, also, please don't cast the return value of malloc() in C.