C++文件操作(2)

版权声明:博主瞎写,随便看看 https://blog.csdn.net/LAN74__/article/details/78787486

这次是要把数据存入二进制文件。。。。但是在写这篇博客的时候,有点小问题,本篇中的数据类型不涉及string,有可能后面要单独开一篇

#include <fstream>
#include <iostream>
#include <string>
using namespace std;
class Users {
public:
    void Register();
    char name[10];
    int id;
    //Users();

};
void Users::Register() {
    cout << "请输入你的名字:";
    cin >> this->name;
    cout << "请输入你的ID:";
    cin >> this->id;
}
int main() {

    Users u,s;
    int len = sizeof(u);
    u.Register();

    #if 1
    fstream my_file("test.dat", ios::out|ios::binary);
    my_file.write((char *)&u, sizeof(u));


    if (my_file.good())
        cout << "成功创建文件" << endl;
    my_file.seekg(0, ios::beg);
    my_file.close();

    fstream my_file1("test.dat", ios::in|ios::binary);
    my_file1.read((char *)&s, sizeof(u));
    cout << "读取名字为:" << s.name << endl;
    cout << "读取ID为:" << s.id << endl;

    #else
    fstream my_file("test.dat", ios::out|ios::in|ios::binary);
    my_file.write((char *)&u, sizeof(u));

    if (my_file.good())
        cout << "成功创建文件" << endl;

    my_file.seekg(0, ios::beg);//读取的时候把流指针移动到文件开头即可,不然。。读取一堆乱码

    my_file.read((char *)&s, sizeof(s));
    cout << "读取名字为:" << s.name << endl;
    cout << "读取ID为:" << s.id << endl;

    my_file.close();
    #endif
    return 0;

}

好。。。看起来很简单是吧

fstream my_file("test.dat", ios::out|ios::in|ios::binary);

都是先fstream类—my_file后面的两个参数,一个是文件路径,一个打开文件方式,这个例子就是读入,写出,二进制(好吧,这里说的很不严谨)

简单的打开文件方式

S
ios::in 为输入打开文件
ios::out 为输出打开文件
ios::app 在文末追加内容
ios::binary 以二进制的方式打开文件

当需要用到多个的时候,他们之间用‘|’或来连接

read函数与write函数

std::istream:: read (char* s, streamsize n);
std::istream:: write (const char* s, streamsize n);
这是原型函数,我们可以看到,有两个参数,s和n
所以呢,在例子中

my_file.write((char *)&u, sizeof(u));
my_file.read((char *)&s, sizeof(s));

我们把对象的地址强制转化为char型,然后再加上其长度

简单的成员函数

S
ios::eof 读到文件结束,返回true
ios::bad 读写过程出错,返回ture
ios::fail 在bad的基础上加上读取格式错误,比如数据类型不匹配
ios::good 只要上述返回值都为false,返回值为true

获取流指针

  • tellg()与tellp()
    返回当前流指针的位置,get流指针或put流指针
  • seekg()与seekp()
    seekg ( pos_type position );
    seekp ( pos_type position );
    这是这俩的原型函数
    参数有偏移量,和流指针起始位置

    s
    ios::beg 文件开头开始位移
    ios::cur 流指针当前位置开始位移
    ios::end 文件尾部开始位移

    像例子中,文件接收数据后,我们要把指针移动到文件开头才能在接下来中读取正确数据

    my_file.seekg(0, ios::beg);

    但是最后的最后,我们不要忘了把这个my_file close掉,不然就没法进行其它对该文件的操作了

猜你喜欢

转载自blog.csdn.net/LAN74__/article/details/78787486