Add simple cat

This commit is contained in:
Trevor Vallender 2024-02-03 13:09:10 +00:00
parent 129a4ecbc9
commit aeba67799b
5 changed files with 64 additions and 0 deletions

View File

@ -4,3 +4,7 @@ Code from programming books I work through—both sample code from the books and
I write myself. I write myself.
## Advanced Programming in the UNIX environment ## Advanced Programming in the UNIX environment
Working through both [the book](http://www.apuebook.com) and [this online course](https://stevens.netmeister.org/631/).

BIN
apitue/01/ls Executable file

Binary file not shown.

27
apitue/01/ls.c Normal file
View File

@ -0,0 +1,27 @@
#include <sys/types.h>
#include <dirent.h>
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char **argv) {
DIR *dp;
struct dirent *dirp;
if (argc != 2) {
fprintf(stderr, "usage: %s dir_name\n", argv[0]);
exit(1);
}
if ((dp = opendir(argv[1])) == NULL) {
fprintf(stderr, "can't open '%s'\n", argv[1]);
exit(1);
}
while ((dirp = readdir(dp)) != NULL) {
printf("%s\n", dirp->d_name);
}
closedir(dp);
return(EXIT_SUCCESS);
}

BIN
apitue/01/simple_cat Executable file

Binary file not shown.

33
apitue/01/simple_cat.c Normal file
View File

@ -0,0 +1,33 @@
// Reads from STDIN only
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#ifndef BUFFSIZE
#define BUFFSIZE 32768
#endif
int main (int argc, char **argv) {
int n;
char buf[BUFFSIZE];
// Cast to void to silence compiler warnings
(void)argc;
(void)argv;
while ((n = read(STDIN_FILENO, buf, BUFFSIZE)) > 0) {
if (write(STDOUT_FILENO, buf, n) != n) {
fprintf(stderr, "Unable to write: %s\n", strerror(errno));
exit(EXIT_FAILURE);
}
}
if (n < 0) {
fprintf(stderr, "Unable to read: %s\n", strerror(errno));
exit(EXIT_FAILURE);
}
return EXIT_SUCCESS;
}