06文件操作

  

1)文本文件

  1)写操作

    步骤

  //1包含头文件
    //2创建输出流对象
    ofstream ofs;
    //3打开文件
    ofs.open("ofs_test.txt", ios::out);
    //4写入数据
    ofs << "这是向文件写入操作" << endl;
    ofs << "姓名:张三" << endl;
    ofs << "性别: 男" << endl;
    //5关闭文件
    ofs.close();

   2)读操作

    步骤

  //1包含头文件
    //2创建流对象
    ifstream ifs;
    //3打开文件,并判断文件是否能打开成功
    ifs.open("ofs_test.txt", ios::in);

    if (!ifs.is_open())
    {
        cout << "打开文件失败" << endl;
        return;
    }
    //4读取数据方式(4种)
    //1)---char buf[]
    char buf[1024] = { 0 };
    while (ifs >> buf)
    {
        cout << buf << endl;
    }
    cout << "--------------------" << endl;
    //2)---getline
    char buf1[1024] = { 0 };
    while (ifs.getline(buf1, sizeof(buf1)))
    {
        cout << buf1 << endl;
    }
    cout << "--------------------" << endl;
    //3)----string
    string str;
    while ( getline(ifs, str))
    {
        cout << str << endl;
    }
    cout << "--------------------" << endl;
    //4)----char----不常用(因为一个字符一个字节,汉语等为2个字节不能正常显示)
    char c;
    while (c = ifs.get() != EOF)//EOF end of file
    {
        cout << c;
    }
    //5关闭文件
    ifs.close();

  注意:1)文件操作必须包含头文件fstream

       2)读/写利用ifstream/ofstream类或者fstream类创建流对象

       2)打开文件,指定打开方式-----读取文件时要用is_open判断文件是否成功打开---读取数据有以上四种方式

       3)操作完成后关闭文件

2)二进制文件操作

    打开方式指定为ios::binary

    写文件:-----利用流对象调用成员函数write

        函数原型:ostream& write(const char *buffer, int len);

        解释:字符常量指针buffer指向内存中一段存储空间。len读写字节数

    读文件:----利用流对象调用成员函数read

        函数原型:istream& read(char *buffer, int len);

        解释:字符指针buffer指向内存中一段存储空间。len读写字节数

原文地址:https://www.cnblogs.com/MissZhang-154/p/13256596.html