Skip to content

Commit

Permalink
Merge pull request #25 from fischerling/improve-text-printing
Browse files Browse the repository at this point in the history
Improve text printing
  • Loading branch information
Galfurian authored Feb 26, 2024
2 parents 1447413 + beacbde commit b617fcc
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 19 deletions.
10 changes: 7 additions & 3 deletions programs/cat.c
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,10 @@ static inline void print_content(const char *path, char *buffer, unsigned buflen
// Open the file.
int fd = open(path, O_RDONLY, 42);
if (fd >= 0) {
ssize_t bytes_read = 0;
// Put on the standard output the characters.
while (read(fd, buffer, buflen) > 0) {
puts(buffer);
while ((bytes_read = read(fd, buffer, buflen)) > 0) {
write(STDOUT_FILENO, buffer, bytes_read);
}
// Close the file descriptor.
close(fd);
Expand All @@ -45,6 +46,7 @@ int main(int argc, char **argv)
return 0;
}
}
int status = 0;
// Prepare the buffer for reading.
char buffer[BUFSIZ];
// Iterate the arguments.
Expand All @@ -60,16 +62,18 @@ int main(int argc, char **argv)

} else if (S_ISDIR(statbuf.st_mode)) {
printf("cat: %s: Is a directory\n\n", argv[i]);
status = 1;

} else if (S_ISLNK(statbuf.st_mode)) {
if (readlink(argv[i], buffer, BUFSIZ)) {
print_content(buffer, buffer, BUFSIZ);
} else {
printf("cat: %s: %s\n\n", argv[i], strerror(errno));
status = 1;
}
}
}
putchar('\n');
putchar('\n');
return 0;
return status;
}
21 changes: 5 additions & 16 deletions programs/man.c
Original file line number Diff line number Diff line change
Expand Up @@ -40,30 +40,19 @@ int main(int argc, char *argv[])
}
else if (argc == 2)
{
char *pager = "cat";
char filepath[PATH_MAX];
strcpy(filepath, "/usr/share/man/");
strcat(filepath, argv[1]);
strcat(filepath, ".man");
int fd = open(filepath, O_RDONLY, 42);
if (fd < 0)
{
printf("%s: No manual entry for %s\n\n", argv[0], argv[1]);
}
else
{
// Prepare the buffer for reading the man file.
char buffer[BUFSIZ];
// Put on the standard output the characters.
while (read(fd, buffer, BUFSIZ) > 0)
{
puts(buffer);
}
// Close the file descriptor.
close(fd);
// Terminate with a pair of newlines.
putchar('\n');
putchar('\n');
printf("%s: No manual entry for %s\n", argv[0], argv[1]);
exit(1);
}
close(fd);
execlp(pager, pager, filepath);
}
return 0;
}

0 comments on commit b617fcc

Please sign in to comment.