C Example to Reverse a file
The idea is to read all the file and when you reach the end(EOF) print them.
#include <stdio.h>
#include <stdlib.h>
void reverse(FILE * file) {
int fscanf_return_value;
char x;
/* read a char */
fscanf_return_value = fscanf(file,"%c",&x) ;
if(fscanf_return_value == EOF) { //fscanf returns EOF as the END OF FILE
return;
}
reverse(file); //Get the next char
//do something with the char e.g. print
putchar(x);
return;
}
int main(int argc, char *argv[]) {
int i;
FILE *fd;
if (argc!=2) {
printf("Usage : \n %s FILENAME\n",argv[0]);
exit(0);
}
if(!(fd=fopen(argv[1],"r"))) {
printf("Opening file error\n");
exit(1);
}
reverse(fd);
printf("\n\n\t---\tenoD - Done\t---\n");
close(fd);
exit(0);
}
To run it just give it argument the name of the file you want. For example if the code above is in a file named reverse.c
and compiled with the command
gcc reverse.c -o reverse
just type in the konsole
./reverse reverse.c
and you will get the output bellow.
If you want to save it to another file the easiest way to do it
is to execute
Example of output is:
./reverse reverse.c >> output.txt
}
;)0(tixe
;)df(esolc
;)"n\---t\enoD - Donet\---t\n\n\"(ftnirp
;)df(esrever
}
;)1(tixe
;)"n\rorre elif gninepO"(ftnirp
{ )))"r",]1[vgra(nepof=df(!(fi
}
;)0(tixe
;)]0[vgra,"n\EMANELIF s% n\ : egasU"(ftnirp
{ )2=!cgra( fi
;df* ELIF
;i tni
{ )][vgra* rahc ,cgra tni(niam tni
}
;nruter
;)x(rahctup
tnirp .g.e rahc eht htiw gnihtemos od//
rahc txen eht teG// ;)elif(esrever
}
;nruter
ELIF FO DNE eht sa FOE snruter fnacsf// { )FOE == eulav_nruter_fnacsf(fi
; )x&,"c%",elif(fnacsf = eulav_nruter_fnacsf
/* rahc a daer */
;x rahc
;eulav_nruter_fnacsf tni
{ )elif * ELIF(esrever diov
>h.bildts< edulcni#
>h.oidts< edulcni#
--- enoD - Done ---
I think it is a simple to understand example.
Another way to do it is to use fseek(FILE,SEEK_END) to move the pointer in the file at the end and then start reading a char,do something with it,use fseek(FILE,-1,SEEK_CUR) to move the pos one char back and do this untill you reach the SEEK_SET.
i hope this was helpful. Please post any comments you have.
No comments for "C Example to Reverse a file"
Post a Comment