Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't write int to file using fwrite

Tags:

c

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?

like image 309
legionar Avatar asked Dec 02 '25 04:12

legionar


2 Answers

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.

like image 67
Don't You Worry Child Avatar answered Dec 06 '25 12:12

Don't You Worry Child


Instead of

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

try

fprintf(keylog, "%d", prevH);
like image 20
Baldrick Avatar answered Dec 06 '25 11:12

Baldrick



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!