How to read .exe in c

妖精的绣舞 提交于 2019-12-13 04:42:15

问题


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:


@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.



来源:https://stackoverflow.com/questions/21766523/how-to-read-exe-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!