简体   繁体   English

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

[英]Reading and Writing to a file in C++ integer by integer

I have a piece of code to write elements of an array to a file (serialize) and then read it back (deserialize) Here it is : 我有一段代码将数组的元素写入文件(序列化),然后将其读回(反序列化),这是:

#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;
}

How to achieve this using the objects ofstream and ifstream in C++? 如何使用C ++中的对象ofstream和ifstream实现此目的?

object streams operator overloading requires to provide an overload for a given type. 对象流运算符重载需要为给定类型提供重载。 Which means you need to wrap your custom array, for instance like 这意味着您需要包装自定义数组,例如

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

and then define the overloads 然后定义重载

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;
}

There is an issue with your code. 您的代码有问题。 serialization and deserialization are not strictly inverse operations. 序列化和反序列化不是严格的逆运算。 This is due to the fact that when reading you have no clue on how many values you are supposed to read. 这是由于以下事实:在读取时,您不知道应该读取多少个值。 Thus trying to serialize your data and then something else and read back will always fail. 因此,尝试先序列化数据,然后再进行其他操作并回读将始终失败。

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

Here not only y ! = b 这里不仅y ! = b y ! = b , but x != a . y ! = b ,但x != a To add insult to the injury, the content of both x and y will be different depending on whether you are c++11 or not . 更糟的是, 取决于您是否为c ++ 11xy的含量也会有所不同

You can use other approach: ostream_iterator and istream_iterator 您可以使用其他方法: 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