繁体   English   中英

用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 y ! = b ,但x != a 更糟的是, 取决于您是否为c ++ 11xy的含量也会有所不同

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM