Adam Muller Adam Muller - 1 month ago 17
C Question

fgetc misses bytes while reading a file

I use the function fgetc to read each byte of a file, and then write it with printf.

I juste noticed that sometimes, fgetc just miss some bytes, when I compare my result with an hex editor.

for example, the first mistake starts around the 118th byte, and a lot of other mistakes randomly ...

Somebody ever experienced this ?

This is the code (Windows)

char main(int argc, char* argv[]) {
FILE* fdIn;
FILE* fdOut;
long size = 0;
long i = 0;
char c = 0;
if (argc == 3) {
if ((fdIn = fopen(argv[1], "rt")) == NULL) {
printf("FAIL\n");
return 0;
}
if ((fdOut = fopen(argv[2], "w+")) == NULL) {
printf("FAIL\n");
return 0;
}
fseek(fdIn, 0L, SEEK_END);
size = ftell(fdIn);
fseek(fdIn, 0L, 0);
fprintf(fdOut, "unsigned char shellcode[%ld] = {", size);
while (i < size) {
c = fgetc(fdIn);
if (!(i % 16))
fprintf(fdOut, "\n\t");
fprintf(fdOut, "0x%02X", (unsigned char)c);
if (i != size - 1)
fprintf(fdOut, ", ");
i++;
}
fprintf(fdOut, "\n};\n");
fclose(fdIn);
fclose(fdOut);
printf("SUCCESS");
system("PAUSE");
}
return 0;
}


Thanks

Answer

Open the file in binary mode.

// if ((fdIn = fopen((char*)argv[1], "rt")) == NULL) { 
//                                 >.< 
if ((fdIn = fopen((char*)argv[1], "rb")) == NULL) {

In text mode, and lile a windows based machine given the "rt", "\r\n" is likely translate into '\n'. IAC, no translations are needed for OP's goal.