JACK M JACK M - 1 month ago 11
C Question

reverse content of file block by block

So here is the program to reverse content of a file block by block.

#include <stdio.h>
#include <stdlib.h>
#define BS 12

void reverse(char * buffer, int size)
{
char tmp;
int i;
for(i = 0; i < size / 2; i++)
{
tmp = (char)buffer[i];
buffer[i] = buffer[size - i - 1];
buffer[size - i - 1] = tmp;
}
}

int main (const int argc, const char** argv)
{
if(argc != 3)
exit(-1);

char * buffer = malloc(BS);
FILE * f1, * f2;
f1 = fopen(argv[1], "r");
f2 = fopen(argv[2], "w");

fseek(f1, 0, SEEK_END);

long i = ftell(f1);
// long f1_len = ftell(f1);
// unsigned char tmp;
int if_end = 1;
int need = 0;
int count;


do
{
i = i - BS;
if(i < 0)
{
need = BS - abs(i);
i = 0;
}
else
need = BS;

fseek(f1, i, SEEK_SET);

if(if_end) // strip EOF
{
count = fread(buffer, need - 1, 1, f1);
if_end = 0;
}
else
count = fread(buffer, need, 1, f1);

reverse(buffer, count);
fwrite(buffer, count, 1, f2);

if(i == 0)
break;
}while(i > 0);


fclose(f1);
fclose(f2);
free(buffer);

return 0;
}


testfile:

$ xxd testfile
0000000: 6162 6364 6566 670a abcdefg.
$ gcc test.c -o test
$ ./test testfile testfile2
$ xxd testfile2
0000000: 61 a


Any idea where is wrong? I have been debugging this for long time.

Answer

Your problem is that fwrite returns the number of successful blocks, not the number of bytes.

So reverse(buffer, count); needs to be reverse(buffer,count * need)

Similairly the write to the output needs to be fwrite(buffer, count * need, 1, f2);

Comments