| io/file-backward.c - Et program der læser en fil baglæns. | Lektion 13 - slide 16 : 32 Program 1 |
/* Echoes a file, in reverse, to standard output */
#include <stdio.h>
#define MAXSTRING 100
int main(void){
char filename[MAXSTRING];
int c;
FILE *ifp;
// Prompt for file name:
fprintf(stderr, "\nInput a filename: ");
scanf("%s", filename);
// Read chars from file in reverse order:
ifp = fopen(filename, "rb"); // MingW: b (for binary) seems necessary.
fseek(ifp, 0, SEEK_END);
fseek(ifp, -1, SEEK_CUR); // Now ready to read last char
while (ftell(ifp) > 0) {
c = getc(ifp);
putchar(c); // Echo on standard output
fseek(ifp, -2, SEEK_CUR);
}
// The only character that has not been printed
// is the very first character in the file. Handle it now:
fseek(ifp, 0, SEEK_SET);
c = getc(ifp);
putchar(c); putchar('\n');
// Close file:
fclose(ifp);
return 0;
}