将float值导出到文件时遇到了一个奇怪的问题.我希望每个浮点数具有相同的长度(显然),但我的程序有时会将其输出为32位数,有时输出为40位数.仍然显示此行为的程序的最小工作示例是:
#include <stdio.h>
const char* fileName = "C:/Users/Path/To/TestFile.txt";
float array [5];
int main(int argc, char* argv [])
{
float temp1 = 1.63006e-33f;
float temp2 = 1.55949e-32f;
array[0] = temp1;
array[1] = temp2;
array[2] = temp1;
array[3] = temp2;
array[4] = temp2;
FILE* outputFile;
if (!fopen_s(&outputFile, fileName, "w"))
{
fwrite(array, 5 * sizeof(float), 1, outputFile);
fclose(outputFile);
}
return true;
}
Run Code Online (Sandbox Code Playgroud)
我希望输出文件包含正好20(5×4)个字节,每个字节代表一个浮点数.但是,我明白了:
8b 6b 07 09 // this is indeed 1.63006e-33f
5b f2 a1 0d 0a // I don't know …Run Code Online (Sandbox Code Playgroud) 在许多项目中,我看到数据对象/结构以二进制模式写入文件,然后再次以二进制模式从文件中检索它们.
我想知道为什么他们在二进制模式下这样做?文本和二进制模式之间的任何性能差异?如果没有,那么何时使用二进制模式或文本模式?
我做过一些像:
FILE* a = fopen("a.txt", "w");
const char* data = "abc123";
fwrite(data, 6, 1, a);
fclose(a);
Run Code Online (Sandbox Code Playgroud)
然后在生成的文本文件中,它就像预期的那样说"abc123".但后来我做了:
//this time it is "wb" not just "w"
FILE* a = fopen("a.txt", "wb");
const char* data = "abc123";
fwrite(data, 6, 1, a);
fclose(a);
Run Code Online (Sandbox Code Playgroud)
并获得完全相同的结果.如果我使用二进制或普通模式读取文件,它也会给我相同的结果.所以我的问题是,有或没有二进制模式的fopening有什么区别.
我在哪里读到有关fopen模式的信息:http://www.cplusplus.com/reference/cstdio/fopen/
我想知道我们用于在 C 中打开文件的模式(文本或二进制)是否真的很重要。
例如,一般情况下,我们使用fread和fwrite来进行二进制模式的读写。当我们以文本模式打开文件时可以使用这些函数吗?
除此之外,一般情况下,我们可以使用fscanf和fprintf来进行文本模式的读写。如果我们以二进制模式打开文件,可以使用这些函数吗?
以文本或二进制模式打开文件会产生什么后果?
在Windows上,我CryptGenRandom在C中使用API(我认为它等同于/dev/random或/dev/urandom在Linux上).为了确认它,我CryptGenRandom在Windows上使用这些随机文件并/dev/urandom在Linux 上读取,并使用分析结果ent.
我用来生成随机文件的代码示例CryptGenRandom(最初来自这里):
#include <windows.h>
static void
secure_entropy(void *buf, size_t len)
{
HCRYPTPROV h = 0;
DWORD type = PROV_RSA_FULL;
DWORD flags = CRYPT_VERIFYCONTEXT | CRYPT_SILENT;
if (!CryptAcquireContext(&h, 0, 0, type, flags) ||
!CryptGenRandom(h, len, buf)) {
printf("failed to gather entropy");
abort();
}
CryptReleaseContext(h, 0);
}
void test4()
{
size_t size = 1 << 20;
FILE *tfile = fopen("random_file", "w");
char *buf = malloc(size); …Run Code Online (Sandbox Code Playgroud) 我正在尝试写入一个包含1126万uint16_t值的数组.总内存大小应为~22 MB.但是,我的文件大小是52MB.我正在使用fprintf将数组写入磁盘.我想也许这些价值观正在被提升.我试图明确但似乎没有任何区别.我文件的大小固执不变.
我究竟做错了什么?代码如下.
#define __STDC_FORMAT_MACROS
...
uint32_t dbsize = 11262336;
uint16_t* db_ = new uint16_t[dbsize_];
...
char fname[256] = "foo";
FILE* f = fopen(fname, "wb");
if(f == NULL)
{
return;
}
fprintf(f, "%i\t", dbsize_);
for(uint32_t i = 0; i < dbsize_; i++)
{
fprintf(f, "%" SCNu16 "", db_[i]);
}
fclose(f);
Run Code Online (Sandbox Code Playgroud) c ×5
c++ ×4
file ×2
binary ×1
binaryfiles ×1
cryptography ×1
file-io ×1
io ×1
random ×1
text ×1
text-files ×1
winapi ×1