I was experimenting with writing a program that would reverse the contents of a file.
So, giving the inputfile with the content “abc” it should make a file with a content “cba”.
Unfortunately, it doesn’t work and I don’t understand why.
Could you guys please help me?
Thanks
EDIT: i forgot to mention that it was a school assignment – and we have to use functions like lseek and open – Please dont posr me that I should’ve used fgetc anfd other functions 🙂
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
void reverse_file(char * in, char * out)
{
int infile, outfile;
infile = open(in, O_RDONLY);
outfile = open(out, O_WRONLY);
char buffer;
char end = EOF;
write(outfile, &end, sizeof(char));
do
{
// seek to the beginning of a file
read(infile, &buffer, sizeof(char));
// printf("the code of a character %d\n", buffer); // returns 10 instead of EOF
lseek(outfile, 0, SEEK_SET);
write(outfile, &buffer, sizeof(char));
} while (buffer != EOF);
close(outfile);
close(infile);
}
int main()
{
reverse_file("tt", "testoutput");
return 0;
}
Your current code (outside the fact that the test for the end of file is wrong), will make a file of one char, because
writeoverwrite the data present in the file at the current position (unless it’s at the end, where it would append).Actually, to reverse the file, you should read it starting from the end.
(Reading char by char is very ineficient with the unix
readandwritesystem calls, so as a second step, you should consider using the C primitives (fopen,fread,fwrite), or do some buffered reads and writes with the unix system calls.)See: