C/如何将布尔值的数组写入文本文件
c/How to write an array of boolean value into a text file?
我有一个很大的布尔值,我想将其写入.txt
文件。
我尝试了 fwrite()
,当我使用 cat
命令打印输出 .txt
文件时,它在屏幕上打印一些奇怪的符号。
我希望它显示为0
和1
。如何做?
bool* tmp = new bool[size]; // tmp has actual values in it, this is just used to show what are tmp and size
FILE* f = fopen("result.txt", "wb");
for (int i=0; i<size; i++) {
fwrite(tmp, sizeof(bool), num_sample_per_point, f);
fwrite("n", sizeof(char), 1, f); // insert new line
}
fclose(f);
另外,我考虑过将这些值转换为int
值,但是太贵了,因为数组的大小很大。
编写t type t type File的二进制表示不会为您提供人类可读的文本文件(type char
除外(。编写具有true的bool
类型,可以产生二进制模式00000001
,并在文件上使用cat
将打印字母1
。
如果您希望该文件包含 0
for false的字母,而1
为true,则必须先转换Bool值。
保持代码样式,看起来像:
int main(void) {
const int size = 3;
bool tmp[size] = {false, true, false};
FILE* f = fopen("result.txt", "w");
for (int i=0; i<size; i++) {
fwrite(tmp[i] ? "1" : "0", sizeof(char), 1, f);
// ^^^^^^^^^^^^^^^^^
// convert bool to letter
}
fwrite("n", sizeof(char), 1, f); // insert new line
fclose(f);
return 0;
}
注意:如果您正在编写C ,则应查看std::ofstream
如果要将人类可读数据保存到文件中,请为文本打开:
FILE* f = fopen("result.txt", "wt");
// ^-----
否则将其写成二进制。 然后,您需要考虑您写的内容的细节。如果您想要布尔值1或0,则需要为此编写代码。
相关文章:
- 2D数组来自文本输入,中间有空格
- 如何将内容数组写入文本文件?
- C++将文本文件中的数据读取到结构数组中
- 将值从二维数组输出到文本文件
- C++ 使用存储在动态数组中的文本文件中的数据查找模式
- C++编程从外部文本文件定义数组大小
- 使用矢量将文本文件中的输入存储到 2D 数组中
- 如何将文本文件的特定行读取到 int 类型的数组中C++?
- 通过分隔符分隔包含 UTF-16 BE 文本的uint8_t数组
- 如何检测将文本文件读入 int 数组的新行
- C++快速将 int 数组内容转储到文本文件中
- 如何将文本文件读取到二维数组中并以 c++ 打印
- 无法将整个文本文件复制到字符数组
- 如何在 c++ 中将文本文件传递到 2D 数组中?
- 是否可以创建一个用户定义的文本,将字符串文本转换为 own 类型的数组?
- 使用空格分隔符从文本文件将对象读入数组
- std::string 参数是如何从原始字符数组文本传递的
- 如何替换QT QML中的变体数组文本
- 视觉C++数组文本
- 仅显示数组文本文件中的第一个字母