Skip to content

Instantly share code, notes, and snippets.

@achequisde
Last active November 7, 2021 00:29
Show Gist options
  • Save achequisde/cf1420434baef8e008fc303bf8983209 to your computer and use it in GitHub Desktop.
Save achequisde/cf1420434baef8e008fc303bf8983209 to your computer and use it in GitHub Desktop.
Simple implementation of tac (reverse cat)
/* This is free and unencumbered software released into the public domain.
*
* Anyone is free to copy, modify, publish, use, compile, sell, or
* distribute this software, either in source code form or as a compiled
* binary, for any purpose, commercial or non-commercial, and by any
* means.
*
* In jurisdictions that recognize copyright laws, the author or authors
* of this software dedicate any and all copyright interest in the
* software to the public domain. We make this dedication for the benefit
* of the public at large and to the detriment of our heirs and
* successors. We intend this dedication to be an overt act of
* relinquishment in perpetuity of all present and future rights to this
* software under copyright law.
*
* 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 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.
*
* For more information, please refer to <http://unlicense.org/> */
#include <sys/stat.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void tac(const char *file_name)
{
FILE *fp = fopen(file_name, "r");
if (fp == NULL) {
perror("Could not open file.\n");
exit(EXIT_FAILURE);
}
int fd = fileno(fp);
if (fd == -1) {
perror("Could not get the file descriptor for file.\n");
exit(EXIT_FAILURE);
}
struct stat buffer;
int err = fstat(fd, &buffer);
if (err == -1) {
perror("Fstat returned an error.\n");
exit(EXIT_FAILURE);
}
size_t file_size = buffer.st_size;
char *reversed_file = (char*)malloc(sizeof(char) * file_size);
file_size--;
for (char ch = fgetc(fp); ch != EOF; ch = fgetc(fp), file_size--)
*(reversed_file + file_size) = ch;
// Remove the newline at the start
memmove(reversed_file, reversed_file + 1, strlen(reversed_file));
printf("%s\n", reversed_file);
fclose(fp);
free(reversed_file);
}
int main(int argc, char* argv[])
{
if (argc <= 1) {
return EXIT_SUCCESS;
}
for (size_t i = 1; i < argc; i++) {
tac(argv[i]);
}
return EXIT_SUCCESS;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment