Reputation: 1409
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?
Upvotes: 1
Views: 3021
Reputation: 97938
#include <stdio.h>
long max(long v1, long v2) { return v1 >= v2 ? v1 : v2; }
long min(long v1, long v2) { return v1 >= v2 ? v2 : v1; }
void invert_bits(char *arr, size_t size);
int main(int argc, char *argv[]) {
size_t read_sz;
FILE * infile = fopen(argv[1], "r");
fseek(infile, 0, SEEK_END);
long file_sz = ftell(infile);
long offset = file_sz;
long total_read = 0;
long num_seeks = 10;
size_t buffer_sz = (file_sz + num_seeks - 1) / num_seeks;
char buffer[buffer_sz];
while (file_sz > total_read) {
if ((offset + num_seeks - 1) / num_seeks < buffer_sz) {
buffer_sz = offset / num_seeks;
}
offset = max(0, offset - buffer_sz);
fseek(infile, offset, SEEK_SET);
read_sz = fread(buffer, 1,
min(buffer_sz, file_sz - total_read), infile);
total_read += read_sz;
invert_bits(buffer, read_sz);
num_seeks--;
}
fclose(infile);
}
void invert_bits(char *arr, size_t size) {
size_t i;
int j;
for (i = size; i > 0; i--) {
char v = arr[i - 1];
char o = 0;
for (j = 0; j < 8; j++) {
o |= v & 1;
v >>= 1;
o <<= 1;
}
printf("%c", o);
}
}
Upvotes: 2