gpt4 book ai didi

VC2012中与fwrite的混淆

转载 作者:太空宇宙 更新时间:2023-11-03 23:28:22 26 4
gpt4 key购买 nike

我需要将一些二进制数据写入文件。格式为 uint64_t

  #include <stdio.h>
#include <assert.h>
typedef unsigned long long uint64_t;

int main()
{
FILE * file = fopen("data","w");assert(file);
uint64_t a[]={16000550, 1051320,14456018, 4743184,11840752 ,4225032,\
13642264,6059108,563784 ,11823354,3989084 ,15759410,\
13413018 ,1582802,1574952 ,1635384,1102996 ,10511428,\
10239562 ,9472574,2641952 ,1350256,3432142 ,9920,11573360,\
12121180,10255874 ,3198684,7628524,16522766,12908660,\
2681374,9482820 ,6354462,15230702 ,16255676,5813862, \
8174782,7642752,7362790,6089340 ,803928,2669686 ,4225032,\
7603956 ,16551562,15734364 ,14424308,12060282 ,572450,\
18432 ,10276902,8134910 ,10749010,14166126 ,1636942,\
5295788 ,12342876,2151156 ,12322948};
for(int i=0;i<sizeof(a)/sizeof(uint64_t);i++)
{
fwrite((char*)&a[i],sizeof(uint64_t),1,file);
}
fclose(file);
}

我发现只有当数组的大小很大时,输出才不符合我的期望,所以我在示例中给出了 60 个 uint64_t

在测试中,我发现它会为 8134910 输出 0000 fe20 7c00 0000。此外,它还存在其他一些错误。在 GCC 中,它运行良好,在 VS2012 中,它运行不佳。

最佳答案

根据您在评论中的反馈,它在 VS2012 中不同的原因是因为文件默认以“文本”模式打开。在此模式下,每个 \n 写入时都会扩展为 \r\n,这会破坏您的数据。

解决方案是显式以二进制方式打开文件:

FILE * file = fopen("data","wb")

引用自 MSDN 关于 tb 可能附加到 mode 的字符:

t

Open in text (translated) mode. In this mode, CTRL+Z is interpreted as an EOF character on input. In files that are opened for reading/writing by using "a+", fopen checks for a CTRL+Z at the end of the file and removes it, if possible. This is done because using fseek and ftell to move within a file that ends with CTRL+Z may cause fseek to behave incorrectly near the end of the file.

In text mode, carriage return–linefeed combinations are translated into single linefeeds on input, and linefeed characters are translated to carriage return–linefeed combinations on output. When a Unicode stream-I/O function operates in text mode (the default), the source or destination stream is assumed to be a sequence of multibyte characters. Therefore, the Unicode stream-input functions convert multibyte characters to wide characters (as if by a call to the mbtowc function). For the same reason, the Unicode stream-output functions convert wide characters to multibyte characters (as if by a call to the wctomb function).

b

Open in binary (untranslated) mode; translations involving carriage-return and linefeed characters are suppressed.

If t or b is not given in mode, the default translation mode is defined by the global variable _fmode.

_fmode 的 MSDN 文档说:

The default setting of _fmode is _O_TEXT for text-mode translation. _O_BINARY is the setting for binary mode.

关于VC2012中与fwrite的混淆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21229458/

26 4 0
文章推荐: angularjs - HTML5 视频无法播放且媒体请求中止
文章推荐: c# - 尝试使用 linq 查询同一文件夹中的多个文本文件
文章推荐: node.js - Nodejs : TypeError: Object # has no method 'endianness'