逐个整数地读取和写入 C++ 中的文件

Reading and Writing to a file in C++ integer by integer

我有一段代码可以将数组的元素写入文件(序列化)然后读回(反序列化) 在这里:

#include<stdio.h>

void serialize(int *arr,int n,FILE *fp)
{
    int i=0;
    for( ; i<=n-1 ; i++)
        fprintf(fp,"%d ",arr[i]); // The elements of array go into the file
}

void deserialize(FILE *fp)
{
    int temp;
    while(1)
    {
        if(fscanf(fp,"%d",&temp))
            printf("%d ",temp);        // The Contents of file tree.txt are written to console
        else
            break;
    }
}


int main()
{
    int arr[] = {20,8,-1,-1,22,-1,-1};

    FILE *fp = fopen("tree.txt", "w");
    if (fp == NULL)
    {
        puts("Could not open file");
        return 0;
    }
    serialize(arr,n, fp);
    fclose(fp);

    fp = fopen("tree.txt", "r");
    deserialize(fp);
    fclose(fp);
    return 0;
}

如何在C++中使用ofstream和ifstream的对象来实现?

对象流运算符重载需要为给定类型提供重载。这意味着您需要包装自定义数组,例如

struct my_array
{
   int *arr;
   int n;
};

然后定义重载

std::ostream& operator<<(std::ostream& os, const my_array& foo)
{
   //same as serialize
   int i=0;
   for( ; i<=foo.n-1 ; i++)
      os << foo.arr[i];
   return os;
}

std::istream& operator>>(std::istream& is, my_array& dt)
{
    //do something 
    return is;
}

您的代码有问题。序列化和反序列化不是严格的逆操作。这是因为在阅读时您不知道应该阅读多少个值。因此,尝试序列化您的数据然后再读取其他内容并回读将总是失败。

fstream s;
my_array a;
bar b;
s << a << b;
...
my_array x;
bar y;
s >> x >> y; //endof, failbit set

这里不仅y ! = b,还有x != a。雪上加霜的是,xywill be different depending on whether you are c++11 or not.

的内容

您可以使用其他方法:ostream_iteratoristream_iterator

#include <fstream>
#include <iostream>
#include <iterator>
#include <algorithm>

int main(int, char **)
{
  int arr[] = {20,8,-1,-1,22,-1,-1};

  // write to console
  std::copy(arr, arr + 7, std::ostream_iterator<int>(std::cout, " "));

  // write on file
  std::cout << std::endl << "Writing on file" << std::endl;

  std::ofstream myOfile("./out.dat");

  if (myOfile.is_open())
  {
    std::ostream_iterator<int> out_iter(myOfile, " ");
    std::copy(arr, arr + 7, out_iter);

    myOfile.close();
  }

  // read from file
  std::cout << std::endl << "Reading from file" << std::endl;

  std::ifstream myIfile("./out.dat");

  if (myIfile.is_open())
  {
    std::copy(std::istream_iterator<int>(myIfile),
              std::istream_iterator<int>(),
              std::ostream_iterator<int>(std::cout, " "));

    myIfile.close();
  }

  return 0;
}