问题
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?
回答1:
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.
回答2:
Instead of
fwrite(&prevH, 1, sizeof(int), keylog);
try
fprintf(keylog, "%d", prevH);
回答3:
With fwrite
you are storing the binary representation. If you want to store a textual representation you can use fprintf
.
回答4:
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/
来源:https://stackoverflow.com/questions/19346269/cant-write-int-to-file-using-fwrite