Skip to main content

/docs/images/banner.jpg

Operating System

LS command

LS

ls - list files in folder

ls

We use C program to list files in a directory. The program is as follows:

#include <stdio.h>
#include <dirent.h>
#include <sys/types.h>
#include <string.h>

int main(int argc, char *argv[]) {
char *dir_path = argv[1];
DIR *dir = opendir(dir_path);
if (dir == NULL) {
perror("opendir failed");
return 1;
}
struct dirent *entry;
while ((entry = readdir(dir)) != NULL) {
if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) {
continue;
}
printf("%s\n", entry->d_name);
}
closedir(dir);
return 0;
}

To compile and run the program, use the following commands(dont copy the $ sign, it represents the terminal prompt):

$ gcc ls.c -o ls
$ ./ls /path/to/directory

This will list all the files in the directory specified.

Questions

What is the use of ls command?
ls command is used to list files in a directory.
What is the difference between ls and ls -a command?

ls command lists all files in a directory whereas ls -a lists all files including hidden files.

What is the use of opendir function?
opendir function is used to open a directory stream.
What is the use of readdir function?

readdir function is used to read the next entry in the directory stream.