Skip to content

Instantly share code, notes, and snippets.

@l0rd
Created April 19, 2012 23:17
Show Gist options
  • Save l0rd/2424814 to your computer and use it in GitHub Desktop.
Save l0rd/2424814 to your computer and use it in GitHub Desktop.
Small C file to reverse file's lines
#include <stdio.h>
#define MAX_SIZE 100
/**
* Recursive function that print
* file lines in reverse order
**/
void reverse_print(FILE* fp) {
char line[MAX_SIZE];
if( fgets(line, MAX_SIZE, fp) == NULL )
return;
else {
reverse_print(fp);
printf(line);
}
return;
}
int main(int argc, char* argv[]) {
FILE *fp;
char filename[MAX_SIZE];
// Check input
if (argc != 2) {
printf( "Missing filename\nUsage: %s filename", argv[0] );
exit(1);
}
// Get input file name
strncpy(filename,argv[1], sizeof(filename)-1);
// Open the file
fp = fopen(filename, "r");
if( fp == NULL ) {
printf("Cannot open file %s", filename) ;
exit(2) ;
}
// Call reverse_print function
reverse_print(fp);
// Close the file
fclose(fp) ;
exit(0);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment