C/如何将布尔值的数组写入文本文件

c/How to write an array of boolean value into a text file?

本文关键字:数组 文本 文件 布尔值      更新时间:2023-10-16

我有一个很大的布尔值,我想将其写入.txt文件。

我尝试了 fwrite(),当我使用 cat命令打印输出 .txt文件时,它在屏幕上打印一些奇怪的符号。

我希望它显示为01。如何做?

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,则需要为此编写代码。