/* The MIT License (MIT) Copyright © 2020-2025 pacman64 Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /* You can build this command-line app by running cc -Wall -s -O3 -march=native -mtune=native -flto -o ./first ./first.c */ #include #include #include #include #include #ifdef _WIN32 #include #include #endif #ifdef RED_ERRORS #define ERROR_STYLE "\x1b[38;2;204;0;0m" #ifdef __APPLE__ #define ERROR_STYLE "\x1b[31m" #endif #define RESET_STYLE "\x1b[0m" #else #define ERROR_STYLE #define RESET_STYLE #endif #define ERROR_LINE(MSG) (ERROR_STYLE MSG RESET_STYLE "\n") #define BAD_ALLOC 2 #ifndef IBUF_SIZE #define IBUF_SIZE (32 * 1024) #endif const char* info = "" "first [lines...] [filenames...]\n" "\n" "Emit up to the first n lines from all the named sources given: if no number\n" "is given, the default is 1. The name `-` stands for the standard input. When\n" "no names are given, the standard input is used by default.\n" ""; // slice is a growable region of bytes in memory typedef struct slice { // ptr is the starting place of the region unsigned char* ptr; // cap is how many bytes the memory region has available size_t cap; } slice; void handle_reader_faster(FILE* w, FILE* r, size_t* count) { unsigned char buf[IBUF_SIZE]; unsigned char last = '\n'; while (!feof(w) && *count > 0) { size_t len = fread(buf, sizeof(buf[0]), sizeof(buf), r); if (len < 1) { break; } for (size_t i = 0; i < len; i++) { if (buf[i] == '\n') { (*count)--; if (*count < 1) { fwrite(buf, 1, i + 1, w); return; } } } fwrite(buf, 1, len, w); last = buf[len - 1]; } if (last != '\n') { (*count)--; fputc('\n', w); } } void handle_reader(FILE* w, FILE* r, slice* line, size_t* count, bool live) { if (!live) { handle_reader_faster(w, r, count); return; } while (!feof(w) && *count > 0) { ssize_t len = getline((char**)&line->ptr, &line->cap, r); if (line->ptr == NULL) { fprintf(stderr, "\n"); fprintf(stderr, ERROR_LINE("out of memory")); exit(BAD_ALLOC); } if (len < 0) { break; } fwrite(line->ptr, 1, len, w); const bool has_lf = len >= 1 && line->ptr[len - 1] == '\n'; if (!has_lf) { fputc('\n', w); } fflush(w); (*count)--; } } // handle_file handles data from the filename given; returns false only when // the file can't be opened bool handle_file(FILE* w, const char* path, slice* line, size_t* n, bool live) { FILE* f = fopen(path, "rb"); if (f == NULL) { fprintf(stderr, ERROR_LINE("can't open file named '%s'"), path); return false; } handle_reader(w, f, line, n, live); fclose(f); return true; } // run returns the number of errors int run(char** args, size_t nargs, FILE* w, size_t* count, bool live_lines) { size_t dashes = 0; for (size_t i = 0; i < nargs; i++) { if (args[i][0] == '-' && args[i][1] == 0) { dashes++; } } if (dashes > 1) { const char* m = "can't use the standard input (dash) more than once"; fprintf(stderr, ERROR_LINE("%s"), m); return 1; } slice line; line.ptr = NULL; line.cap = 0; if (live_lines) { line.cap = 32 * 1024; line.ptr = malloc(line.cap); if (line.ptr == NULL) { fprintf(stderr, ERROR_LINE("out of memory")); exit(BAD_ALLOC); } } size_t errors = 0; for (size_t i = 0; i < nargs && !feof(w) && *count > 0; i++) { if (args[i][0] == '-' && args[i][1] == 0) { handle_reader(w, stdin, &line, count, live_lines); continue; } if (!handle_file(w, args[i], &line, count, live_lines)) { errors++; } } // use stdin when not given any filepaths if (nargs < 1) { handle_reader(w, stdin, &line, count, live_lines); } free(line.ptr); return errors; } int main(int argc, char** argv) { #ifdef _WIN32 setmode(fileno(stdin), O_BINARY); // ensure output lines end in LF instead of CRLF on windows setmode(fileno(stdout), O_BINARY); setmode(fileno(stderr), O_BINARY); #endif if (argc > 1) { if ( strcmp(argv[1], "-h") == 0 || strcmp(argv[1], "-help") == 0 || strcmp(argv[1], "--h") == 0 || strcmp(argv[1], "--help") == 0 ) { fprintf(stdout, "%s", info); return 0; } } size_t nargs = argc - 1; char** args = argv + 1; size_t count = 1; if (nargs > 0) { char* end; const ssize_t n = strtol(argv[1], &end, 10); if (*end == 0 && argv[1] != end) { count = n > 0 ? (ssize_t)n : 0; nargs--; args++; } } if (nargs > 0 && strcmp(args[0], "--") == 0) { nargs--; args++; } const bool live_lines = lseek(fileno(stdout), 0, SEEK_CUR) != 0; if (!live_lines) { setvbuf(stdout, NULL, _IOFBF, 0); } return run(args, nargs, stdout, &count, live_lines) == 0 ? 0 : 1; }