# Reading from text file and printing it in IDA Pro

I have a text.txt file and I want to read it and print its content in the Output Window of IDA Pro (Free version).

I wrote an .idc script as follows:

#include <idc.idc>

static main() {
auto fp;
auto toPrint;

fp = fopen("C:\Users\bob\text.txt", "r"); // fp is a file handle

toPrint = fgetc(fp);

Message("%s is the string\n", toPrint);

}


But it gives me an unknown character as shown above. I also tried using toPrint = readstr(fp), but it does not work. (same unknown character)

PS: I'm analysing a 32 bit PE file. I could not use IDAPython, as I'm using the x64 free version, so I have to resort to IDC. Any help appreciated.

The variant below works for me.

static main() {
auto fp;
auto toPrint;
fp = fopen("C:\\Users\\[cenzored]\\desktop\\text.txt", "r"); // fp is a file handle
do {
if (toPrint != -1)Message(toPrint);
} while (toPrint != -1);
}


Actually there are 3 differences between your code and working variant:

• it uses readstr which returns string
• It avoids using format string in Message function (but Message("%s", toPrint) works too)
• As in normal C I use double slash (\\ instead of \) for the path of the file. This is probably an initial cause of your problem: symbols preceded by single slash are interpreted as escape sequences which means that the file name was interpreted incorrectly and was not opened.

Using fgetc in a way you did is also incorrect because it returns long or character, not a string, and Message function probably interprets is as a pointer. I checked this on IDA 6.9. In a later versions it is probably better to detect an EOF by value_is_string function for this.

• @w s Thank you for the help; I realised my mistake. Say, can you convert a string into an integer in IDC? eg. from '1510' to 1510? – Kyoma May 24 '18 at 15:31
• @w s Nvm, got it. Use 'atol' command. – Kyoma May 24 '18 at 15:42