JACK M JACK M - 1 month ago 10
Linux Question

how to get rid of that "end of text"

I am writing a small program in C to reverse content of input file and write to output file.

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

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

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

fseek(f1, 0, SEEK_END);

long i = 0, j = 0;
long f1_len = ftell(f1);
unsigned char tmp;

// while(i >= 0)
// {
for(i = ftell(f1), j = 0; i >= 0 && j <= BS - 1; i--, j++)
{
fseek(f1, i, SEEK_SET);
tmp = fgetc(f1);

if(i == f1_len || tmp == (unsigned char)0x03)
continue;
else
buffer[j] = tmp;
}
if(j == BS - 1)
fwrite(buffer, BS, 1, f2);
else
fwrite(buffer, j, 1, f2);

fflush(f2);
// }

fclose(f1);
fclose(f2);

return 0;
}


testfile:

$ xxd testfile
0000000: 6162 6364 6566 670a abcdefg.


test:

$ gcc test.c -o test
$ test testfile testfile2
$ xxd testfile2
0000000: 030a 6766 6564 6362 61 ..gfedcba


Why is there a '0x03'? I already wrote
tmp == (unsigned char)0x03
to get rid of that char, right?

Answer

As already mentioned 0x03 is uninitialized memory. Furthermore, you have another problem: fseek(f1,ftell(f1),SEEK_SET) moves the file position to the end. The next fgetc() will return EOF. Therefore, your loop should look like this:

for(i = ftell(f1)-1, j = 0; i >= 0 && j <= BS - 1; i--, j++) {....}