..
Unix Cat in C
My crummy cat rewrite
Cat is a core utility from unix like operating systems that echoes the text you give it into ‘stdout’. You already know this, but have you ever wrote a clone of it? Most likely also yes because it’s a very nice way to understand file I/O in the language you are using. Here is my implementation
/*
* Crappy Cat
* Author exit0ne
* Date Oct 16 24
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define ARGUMENT_ERROR 1
#define FILE_IO_ERROR 2
int main(int argc, char **argv)
{
/* Muh variables */
FILE *filePtr;
const char *filePath;
char curChar;
/* Muh Argsssss */
if (argc < 2) {
printf("Argument error\n");
return ARGUMENT_ERROR;
}
/* Call the end user a big dummy for asking for help in this cruel world */
if (strcmp(argv[1], "-h") == 0 || strcmp(argv[1], "--help") == 0
|| strcmp(argv[1], "-help") == 0 || strcmp(argv[1], "help") == 0) {
puts("It's cat are you stupid?");
puts("Why would you ever need help with this?");
return 0;
}
/* Print ze files from ze argument vector and consume ze bugs */
for (int i = 1; i < argc; ++i) {
filePath = argv[i];
filePtr = fopen(filePath, "r");
if (filePtr == NULL) {
printf("File I/O error\n");
return FILE_IO_ERROR;
}
while ((curChar = fgetc(filePtr)) != EOF)
putchar(curChar);
fclose(filePtr);
}
return 0;
}
BUUUUUT!!!!
Even with a program as seemingly simple as cat, there are complexities. For example, there are a good number of arguments and functionalities from the POSIX standard for cat that I did not put into my clone.
WHY???!?!?!?!?!?!?!!?!?!?
I wrote this cat clone so I can get used to file I/O and to port to Golang. That’s it, have a good one, two, three, four, five, six, se………….