vector container file operations

Occupy the entire container can not write the entire file in memory, since each cell in addition to the container pointer there.
Therefore, it should be put in a single unit.
(When the pointer to the address before re-use has been abolished)

Writes:

#include<iostream>
#include<algorithm>
#include <vector>
#include <fstream>
using namespace std;

int main()
{
    int a[]={1,2,3,4,5};
    vector<int>A(a,a+5);
    ofstream in("lala.dat"); 
    int i=A.size()-1;
    while(!A.empty())
    {
        in.write((char*)&A[i],sizeof(A[i])); //必须把地址转化成(char*)类型
        A.pop_back();     
        i--;   
    } 
    in.close();
    return 0;
}

Here before write () function does not cover, it will continue to write it down

Read operation:

#include<iostream>
#include<algorithm>
#include <vector>
#include <fstream>
using namespace std;

int main()
{
   vector<int>A;
    ifstream in("lala.dat");
    int a;
    while (in.peek()!=EOF)  //这里不用eof()
    {
        in.read((char*)&a,sizeof(int));
        A.push_back(a);
    }
    cout<<A[0];
    in.close();
    return 0;
}

Reason not to use eof (): The last part will result in repeated reading.
Because eof () is a character you can not read the file before returning true.
However, there is a terminator end of the file , so the file has not been mistaken eof end of the reading, so that repeat.

The peek (), the character if you want to visit is end of file, the function value is EOF (-1).
But it only observation , the pointer remains in the current location, which also can be seen, there is a read () function pointer movement

Ps: Add here to read the debug view of the entire container (can not read the memory)
Here Insert Picture Description

Guess you like

Origin blog.csdn.net/a10201516595/article/details/93380676
Recommended