Program that reads its own .exe file

Oct 19, 2015 at 4:39pm
I need help making a program that can read its own .exe file, and then writes out the ASCII codes inside it.

#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
string filename;
string line;
filename = "C:\\Users\\march_000\\Documents\\Visual Studio 2015\\Projects\\lab 5 part 2\\Debug";
ifstream in(filename);
while (!in.eof()) {
getline(in, line);
cout << line << "\n";
}
in.close();
return 0;
}
This is what I have so far. Does this look right, if not how can I correct. If/when correct where do I go from here?
Thank you to all of those who help
Oct 19, 2015 at 5:38pm
An executable file contains primarily of binary data (instructions), although there are regions that contain ASCII data. Your program makes no distinction between ASCII and non-ASCII data. Your cout statement is going to output both ASCII and non-ASCII data.

Additionally, using eof() as a while condition is incorrect. eof is set only AFTER attempting a read. Therefore if your getline fails (sets eof), you make an extra pass through the loop with whatever happens to be in line from the last iteration. Lines 19-20 should be:
1
2
 
  while (getline(in, line))


PLEASE USE CODE TAGS (the <> formatting button) when posting code.
It makes it easier to read your code and also easier to respond to your post.
http://www.cplusplus.com/articles/jEywvCM9/
Hint: You can edit your post, highlight your code and press the <> formatting button.
Last edited on Oct 19, 2015 at 5:39pm
Oct 19, 2015 at 6:46pm
Thank you I have made those changes. Do you have any suggestions on how to cout only the ASCII?
Oct 19, 2015 at 8:55pm
Iterate through each line and replace the non-ASCII characters with spaces.
See the following template for classifying characters.
http://www.cplusplus.com/reference/locale/ctype/?kw=ctype

Note that getline by default reads characters up until a \n character. Given that you're reading primarily binary data, the length of line can vary widely. You would be better off using in.read() to read a fixed length buffer.

Last edited on Oct 20, 2015 at 12:54am
Topic archived. No new replies allowed.