How to read .exe in c

2019-09-07 08:25发布

I'm on a little project of making a little compressor program. For that I want to read a file, say an .exe, and parse it char by char and use some simple dictionary algorithm to encrypt it.

For reading the file I just thout in using a simple code I found:

 char *readFile(char *fileName)
{
    FILE *file;
    char *code = malloc(10000* sizeof(char));
    file = fopen(fileName, "rb");
    do
    {
      *code++ = (char)fgetc(file);

    } while(*code != EOF);

    return code;

}

My problem is that it's seems imposible to read an .exe or any file at all. When making a printf() of "code" nothing is writen.

What can I do?

1条回答
一夜七次
2楼-- · 2019-09-07 09:05

@BLUEPIXY well identified a code error. See following. Also you return the end of the string and likely want to return the beginning.

do {
  // *code++ = (char)fgetc(file);
  *code = (char)fgetc(file);
// } while(*code != EOF);
} while(*code++ != EOF);

Something to get you started reading any file.

#include <stdio.h>
#include <ctype.h>

void readFile(const char *fileName) {
  FILE *file;
  file = fopen(fileName, "rb");
  if (file != NULL) {
    int ch;
    while ((ch = fgetc(file)) != EOF) {
      if (isprint(ch)) {
        printf("%c", ch);
      }
      else {
        printf("'%02X'", ch);
        if (ch == '\n') {
          fputs("\n", stdout);
        }
      }
    fclose(file);
  }
}

When reading a binary file char-by-char, code typically receives 0 to 255 and EOF, 257 different values.

查看更多
登录 后发表回答