Skip to content

Instantly share code, notes, and snippets.

@AdriDevelopsThings
Created February 29, 2024 22:17
Show Gist options
  • Save AdriDevelopsThings/53ef80790dbb2145e87e3a118ebb966f to your computer and use it in GitHub Desktop.
Save AdriDevelopsThings/53ef80790dbb2145e87e3a118ebb966f to your computer and use it in GitHub Desktop.
My self written cat implementation
#include <stdint.h>
#include <stdio.h>
int main(int argc, char* argv[]) {
int file_index = 0; // index of the current file
while (file_index + 1 < argc || file_index == 0) {
FILE *file; // contains the pointer to the file
if (file_index + 1 == argc) { // no file path is given, use stdin
file = stdin;
} else { // file path is given, argv[file_index + 1] is file path
file = fopen(argv[file_index + 1], "r");
if (file == NULL) { // check for an error
perror("error while reading file");
return 1;
}
}
// iterate over bytes
while (1) {
uint8_t buf[256]; // read in 256 byte steps
int size = fread(buf, sizeof(uint8_t), 256, file);
if (size < 0) {
perror("error while reading from file");
return 1;
}
if (fwrite(buf, sizeof(uint8_t), size, stdout) < 0) {
perror("error while writing to stdout");
return 1;
}
if (size < 256) { // file reached the end
break;
}
}
file_index++;
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment