5 文件操作

 

 

C++中有一个文件流:fstream

操作文件的三大类:

  ofstream:写操作,文件的输出流

  ifstream:读操作

  fstream:读写操作

 

 

 

 

 

 

 

#include<iostream>
#include<fstream>

using namespace std;

// 文本文件中的写文件
void test01()
{
    // 1.包含头文件 fstream
    
    // 2.创建流对象
    ofstream ofs;
    // 3.指定打开方式
    ofs.open("test.txt", ios::out); // 不指定目录,默认项目路径一致
    // 4.写内容
    ofs << "姓名:张三" << endl;
    ofs << "性别:男" << endl;
    ofs << "年龄:18" << endl;
    // 5.关闭文件
    ofs.close();

}

int main()
{
    test01();
    return 0;
}

 

 

 

 

#include<iostream>
#include<fstream>
#include<string>
using namespace std;

// 文本文件中的读文件
void test01()
{
    // 1.包含头文件 fstream
    
    // 2.创建流对象
    ifstream ifs;
    // 3.打开文件,并判断是否打开成功
    ifs.open("test.txt", ios::in); // 不指定目录,默认项目路径一致
    if (!ifs.is_open())
    {
        cout << "文件打开失败" << endl;
        return;
    }
    // 4.写内容
    // 第一种方式读
    //char buf[1024] = { 0 };
    //while (ifs >> buf) // 读到头了,会返回一个假的标记
    //{
    //    cout << buf << endl;
    //}
    // 第二种方式读
    /*char buf[1024] = { 0 };
    while (ifs.getline(buf, sizeof(buf)))
    {
        cout << buf << endl;
    }*/
    // 第三种方式读
    /*string buf;
    while (getline(ifs, buf))
    {
        cout << buf << endl;
    }*/
    // 第四种方式
    char c;
    while ((c = ifs.get()) != EOF) // 每次一个字符读  EOF: end of file 判断是否读到文件尾部
    {
        cout << c;
    }

    // 5.关闭文件
    ifs.close();

}

int main()
{
    test01();
    return 0;
}

 

 

 

 

#include<iostream>
#include<fstream>
#include<string>
using namespace std;

// 二进制 写文件
class Person
{
public:
    char m_Name[64];
    int m_Age;
};


void test01()
{
    // 1.包含头文件 fstream
    
    // 2.创建流对象
    ofstream ofs;
    // 3.打开文件
    ofs.open("person.txt", ios::out | ios::binary);
    // 4.写内容
    Person p = { "张三", 18 };
    ofs.write((const char*)& p, sizeof(Person));
    // 5.关闭文件
    ofs.close();
}

int main()
{
    test01();
    return 0;
}

 

 

 

 

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

// 二进制 读文件
class Person
{
public:
    char m_Name[64]; // 文件操作时候,最好别用string
    int m_Age;
};


void test01()
{
    // 1.包含头文件 fstream
    
    // 2.创建流对象
    ifstream ifs;
    // 3.打开文件,判断是否打开成功
    ifs.open("person.txt", ios::in | ios::binary);
    if (!ifs.is_open())
    {
        cout << "文件打开失败" << endl;
        return;
    }
    // 4.读内容
    Person p;
    ifs.read((char*)& p, sizeof(Person));
    cout << p.m_Name << endl;
    cout << p.m_Age << endl;
    // 5.关闭文件
    ifs.close();
}

int main()
{
    test01();
    return 0;
}

posted @ 2021-01-15 11:28  不妨不妨,来日方长  阅读(86)  评论(0编辑  收藏  举报