Files
MentOS/programs/cat.c
T
Enrico Fraccaroli (Galfurian) 50569ed1c8 Fix cat to handle symlinks correctly.
2024-03-01 13:51:06 -05:00

86 lines
2.5 KiB
C

/// @file cat.c
/// @brief `cat` program.
/// @copyright (c) 2014-2024 This file is distributed under the MIT License.
/// See LICENSE.md for details.
#include "io/debug.h"
#include "stddef.h"
#include <fcntl.h>
#include <stdio.h>
#include <string.h>
#include <sys/unistd.h>
#include <strerror.h>
#include <sys/stat.h>
int main(int argc, char **argv)
{
if (argc < 2) {
printf("cat: missing operand.\n");
printf("Try 'cat --help' for more information.\n\n");
return 1;
}
// Check if `--help` is provided.
for (int i = 1; i < argc; ++i) {
if ((strcmp(argv[i], "--help") == 0) || (strcmp(argv[i], "-h") == 0)) {
printf("Prints the content of the given file.\n");
printf("Usage:\n");
printf(" cat <file>\n\n");
return 0;
}
}
int fd;
// Prepare the buffer for reading.
char buffer[BUFSIZ];
// Iterate the arguments.
for (int i = 1; i < argc; ++i) {
// Create the stat buffer.
stat_t statbuf;
// Initialize the file path.
char *filepath = argv[i];
// Stat the file.
if (stat(argv[i], &statbuf) == -1) {
printf("cat: %s: %s\n\n", argv[i], strerror(errno));
continue;
}
// Check if it is a link.
if (S_ISLNK(statbuf.st_mode)) {
// Read the content of the link.
if (readlink(filepath, buffer, BUFSIZ) < 0) {
printf("cat: %s: %s\n\n", filepath, strerror(errno));
continue;
}
// Change the filepath.
filepath = buffer;
// Run the stat again, with the real file.
if (stat(filepath, &statbuf) == -1) {
printf("cat: %s: %s\n", filepath, strerror(errno));
continue;
}
}
// Check if it is a directory.
if (S_ISDIR(statbuf.st_mode)) {
printf("cat: %s: Is a directory\n", filepath);
continue;
}
// If it is a regular file, open the file in read-only.
if (S_ISREG(statbuf.st_mode)) {
fd = open(filepath, O_RDONLY, 0);
}
if (fd < 0) {
printf("cat: %s: %s\n", filepath, strerror(errno));
continue;
}
ssize_t bytes_read = 0;
// Put on the standard output the characters.
while ((bytes_read = read(fd, buffer, BUFSIZ)) > 0) {
write(STDOUT_FILENO, buffer, bytes_read);
}
close(fd);
}
putchar('\n');
return 0;
}