legionar
legionar

Reputation: 75

Can't write int to file using fwrite

I'm trying to format my keylog output so it shows time:

        t = time(0);
        now = localtime(&t);


        if(now->tm_min != prevM && now->tm_hour != prevH)
        {
            prevM = now->tm_min;
            prevH = now->tm_hour;

            fwrite("[", 1, sizeof(WCHAR), keylog);
            fwrite(&prevH, 1, sizeof(int), keylog);
            fwrite("]", 1, sizeof(WCHAR), keylog);
            fwrite(" ", 1, sizeof(WCHAR), keylog);
            fflush(keylog);
        }

but instead of readable number I get "[ DLE NUL ] " written in my file, where DLENUL is question mark.

How do I make it to write a readable number?

Upvotes: 2

Views: 4871

Answers (4)

user2876375
user2876375

Reputation: 341

As others have already suggested, you could use fprintf when writing text to a file.

More specifically, when writing WCHARs you can use either:

fwprintf(file, L"%c\n",outputChar);

or:

fprintf(file, "%lc", outputChar);

For more information, have a look at the documentation of the function: http://www.cplusplus.com/reference/cwchar/fwprintf/

Upvotes: 1

0xF1
0xF1

Reputation: 6116

Use fprintf as others are also suggesting.

Reason:
fwrite is generally used to write in binary files to write blocks of same type of data.

The data you are writing looks like a character string, you can use fprintf with following syntax to write your complete data in the file.

 fprintf(keylog, "[%d] ", prevH);

It seems you are writing wide characters (as you use wchar). You can use different format specifiers accordingly.

Upvotes: 5

Mauro H. Leggieri
Mauro H. Leggieri

Reputation: 1104

With fwrite you are storing the binary representation. If you want to store a textual representation you can use fprintf.

Upvotes: 3

Baldrick
Baldrick

Reputation: 11840

Instead of

fwrite(&prevH, 1, sizeof(int), keylog);

try

fprintf(keylog, "%d", prevH);

Upvotes: 3

Related Questions