Created
October 19, 2018 15:17
-
-
Save t0mdicks0n/273931468fce44a069852a52b8fb688a to your computer and use it in GitHub Desktop.
Ghetto implementation in C of native "ls" command in Unix. Compile and run with: gcc -o cmd cmd.c && ./cmd ls
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <glob.h> | |
#include <string.h> | |
void ls () { | |
glob_t glob_result; | |
// Display all files by passing * to glob | |
glob("*", GLOB_TILDE, NULL, &glob_result); | |
// Iterate over the files in the current directory | |
for (unsigned int i = 0; i < glob_result.gl_pathc; ++i) { | |
// Print the file names, just like native ls command | |
printf("%s\n", glob_result.gl_pathv[i]); | |
} | |
} | |
int main(int argc, char *argv[]) | |
{ | |
if (argc == 2) { | |
// Do a string compare to check if argument is ls | |
if (! strcmp(argv[1], "ls")) { | |
ls(); | |
} | |
// TODO: Add more possible arguments here | |
} | |
else if (argc > 2) { | |
printf("Too many arguments supplied."); | |
printf("This program only handles one argument.\n"); | |
} | |
else { | |
printf("Provide an argument, for example ls\n"); | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment