Skip to content

Instantly share code, notes, and snippets.

@john302

john302/myls.c Secret

Created April 3, 2023 02:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save john302/85da5593b180e84d12f75b10471b830f to your computer and use it in GitHub Desktop.
Save john302/85da5593b180e84d12f75b10471b830f to your computer and use it in GitHub Desktop.
This is a simple version of ls(1) using C.
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/********************************************************************
* Description: A version of LS written in C.
* Author: John Cartwright <>
* Created at: Mon Apr 3 10:38:18 AEST 2023
* Computer: localhost.localdomain
* System: Linux 5.14.0-162.18.1.el9_1.x86_64 on x86_64
*
* Copyright (c) 2023 John Cartwright All rights reserved.
*
********************************************************************/
#include <dirent.h>
#include <stdio.h>
#include <sys/stat.h>
#include <string.h>
#include <limits.h>
void list_files(const char *path) {
struct dirent *entry;
struct stat file_stat;
char full_path[PATH_MAX];
DIR *dir = opendir(path);
if (dir == NULL) {
perror("opendir");
return;
}
while ((entry = readdir(dir)) != NULL) {
if (strcmp(entry->d_name, ".") == 0) {
continue;
}
snprintf(full_path, sizeof(full_path), "%s/%s", path, entry->d_name);
if (stat(full_path, &file_stat) < 0) {
perror("stat");
continue;
}
printf("%s", S_ISDIR(file_stat.st_mode) ? "d" : "-");
printf("%s", (file_stat.st_mode & S_IRUSR) ? "r" : "-");
printf("%s", (file_stat.st_mode & S_IWUSR) ? "w" : "-");
printf("%s", (file_stat.st_mode & S_IXUSR) ? "x" : "-");
printf("%s", (file_stat.st_mode & S_IRGRP) ? "r" : "-");
printf("%s", (file_stat.st_mode & S_IWGRP) ? "w" : "-");
printf("%s", (file_stat.st_mode & S_IXGRP) ? "x" : "-");
printf("%s", (file_stat.st_mode & S_IROTH) ? "r" : "-");
printf("%s", (file_stat.st_mode & S_IWOTH) ? "w" : "-");
printf("%s", (file_stat.st_mode & S_IXOTH) ? "x" : "-");
printf(" %ld ", file_stat.st_size);
printf("%s\n", entry->d_name);
}
closedir(dir);
}
int main(int argc, char *argv[]) {
if (argc == 1) {
list_files(".");
} else {
printf("%s", argv[1]);
list_files(argv[1]);
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment