简体   繁体   English

无法使用 fwrite 将 int 写入文件

[英]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.但是我在我的文件中写入了“[ DLE NUL ]”,而不是可读数字,其中 DLENUL 是问号。

How do I make it to write a readable number?我如何让它写一个可读的数字?

Use fprintf as others are also suggesting.其他人也建议使用fprintf

Reason:原因:
fwrite is generally used to write in binary files to write blocks of same type of data. fwrite一般用于在二进制文件中写入相同类型的数据块。

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和以下语法将您的完整数据写入文件。

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

It seems you are writing wide characters (as you use wchar ).看来您正在编写宽字符(当您使用wchar )。 You can use different format specifiers accordingly.您可以相应地使用不同的格式说明符。

With fwrite you are storing the binary representation.使用fwrite您正在存储二进制表示。 If you want to store a textual representation you can use fprintf .如果要存储文本表示,可以使用fprintf

Instead of而不是

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

try试试

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

As others have already suggested, you could use fprintf when writing text to a file.正如其他人已经建议的那样,您可以在将文本写入文件时使用 fprintf。

More specifically, when writing WCHARs you can use either:更具体地说,在编写 WCHAR 时,您可以使用:

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/有关更多信息,请查看该函数的文档:http ://www.cplusplus.com/reference/cwchar/fwprintf/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM