I need to write a program which reverses the order of the bytes in a given binary file. It accepts the file name in the command line. In addition it can use file positioning functions such as fseek no more than a fixed number of times.
Here is a code which I wrote which does not use it a fixed number of times:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(int argc, char** argv) {
if (argc>2) {
printf("Please enter a valid file name");
return 1;
} else {
FILE* file;
file=fopen(argv[1], "r");
if (file==NULL) {
printf("Please enter a valid file name");
return 1;
} else {
FILE* fileBackUp;
fileBackUp=fopen("c:\backupFile.txt", "w+");
fseek(file, 0, SEEK_END);
fseek(file, -1, SEEK_CUR);
while (ftell(file)>=0) {
int c= fgetc(file);
fputc(c, fileBackUp);
fseek(file, -2, SEEK_CUR);
}
fseek(fileBackUp, 0, SEEK_SET);
int c;
while (!feof(fileBackUp)) {
c=fgetc(fileBackUp)
fputc(c,file);
}
fclose(fileBackUp);
fclose(file);
}
}
return 1;
}
It uses an extra file for it. I surely believe that there's a shorter elegant way to do that with a fewer steps as requested. Any suggestions?
Another thing: It seems that the first condition is always being filled, how come?