|
CS456 - Systems Programming
Spring 2025
|
Displaying ./code/ls/ls_simple.c
/*
an extremely simplified version of the ls command,
it works, but a lot of stuff is missing, and there are bugs where
segmentation faults will result. see notes below the main function
*/
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <sys/types.h>
#include <string.h>
int main(int argc, char **argv){
DIR *mydir; //defining a pointer to a directory
struct dirent *file; //accessing the dirent struct, defined in dirent.h
char filename[512]; //buffer for filename
//have it print the current directory, if no filename given,
// otherwise print the directory specified
if(argc < 2)
strcpy(filename, ".");
else
strcpy(filename, argv[1]);
mydir = opendir(filename);
// then we will run through the directory, printing the directory contents
while((file = readdir(mydir)) != NULL){
printf("%s\n", file->d_name);
}
//we're done, so close the directory
closedir(mydir);
return 0;
}
/*
THINGS TO DO TO IMPROVE THIS
1. if no directory is specified, just print the current directory - Done
2. if specified file isn't a directory, say so
3. handle arguments given at the command line,
- like -l and -a,
- or both at the same time
- or neither
Things to know/learn:
- how ls -l is structured (from left to right):
- file type
- permissions
- number of links / directories inside the directory
- the group this file belongs to
- size in bytes
- date last modified
- the file name
- how to tell if something is a directory or not (what function can we use?)
- how to tell our program that the argument is an option, and this argument is our file
- should already be familiar with the stat struct
- the dirent struct and dirent.h header
- there are also structs that store user and group information
- passwd struct, defined in pwd.h
- group struct, defined in grp.h
-may want to know how to know how ctime function works as well
*/
|