用C ++整数读取和写入文件

时间:2015-11-25 11:10:07

标签: c++ file fstream ifstream ofstream

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

#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对象实现这一目标?

2 个答案:

答案 0 :(得分:3)

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

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。要加重伤害,xy will be different depending on whether you are c++11 or not的内容。

答案 1 :(得分:2)

您可以使用其他方法: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;
}