簡體   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