C++学习笔记四之文件操作

一、文本文件---写文件

1)写文件步骤

2) 文件打开方式

3)代码实例

二、文本文件---读文件

 

三、二进制文件---写文件

四、二进制文件---读文件

 

C++中对文件操作需要包含头文件<fstream>;

文件类型分为两种:文本文件和二进制文件;

操作文件的三大类:1.ofstream(写操作);2.ifstream(读操作);3.fstream(读写操作)。

一、文本文件---写文件

1)写文件步骤:

①包含头文件#include<fstream>

②创建流对象 ofstream ofs;

③打开文件ofs.open("path", 打开方式);

④写数据ofs<<"写入的数据";

⑤关闭文件ofs.close();

2)文件打开方式

注:文件打开方式可以配合使用,利用 | 操作符。例如:用二进制文件写文件ios::binary | ios::out。

3)代码实例

#include<iostream>
#include<string>
#include"A.h"
#include<fstream>//1.包含头文件
using namespace std;

int main()
{
    //②创建流对象 ofstream ofs;
    ofstream ofs;

    //③打开文件ofs.open("path", 打开方式);
    ofs.open("test.txt", ios::out);

    //④写数据ofs << "写入的数据";
    ofs << "hello world!";

    //⑤关闭文件ofs.close();
    ofs.close();

    system("pause");
    return 0;
}

 

二、文本文件---读文件

1)读文件步骤

①包含头文件#include<fstream>

②创建流对象 ifstream ifs;

③打开文件并判断文件是否打开成功 ifs.open("path", 打开方式);

④读文件(四种方式读取)

⑤关闭文件ifs.close();

2)代码实例

#include<iostream>
#include<string>
#include"A.h"
#include<fstream>//1.包含头文件
using namespace std;

int main()
{
    //②创建流对象 ofstream ofs;
    ifstream ifs;

    //③打开文件并判断文件是否打开成功 ifs.open("path", 打开方式);
    ifs.open("test.txt", ios::in);
    if (!ifs.is_open())
    {
        cout << "文件打开失败!" << endl;
        system("pause");
        return 0;
    }

    //④读数据
    //法一
    /*char buf[1024] = { 0 };
    while (ifs >> buf)
    {
        cout << buf << endl;
    }*/

    //法二
    /*char buf[1024] = { 0 };
    while (ifs.getline(buf,sizeof(buf)))
    {
        cout << buf << endl;
    }*/
    //法三
    /*string str;
    while (getline(ifs, str))
    {
        cout << str << endl;
    }*/
    //法四
    char c;
    while ((c=ifs.get())!=EOF)//EOF:end of file
    {
        cout << c << endl;
    }

    //⑤关闭文件ofs.close();
    ifs.close();

    system("pause");
    return 0;
}

 

三、二进制文件---写文件

①打开方式指定为  ios::binary | ios::out ;

②调用write函数写文件:ostream &write(const char* buf, int len);

四、二进制文件---读文件

①读文件调用函数read:istream &read(char* buf, int len);

 

posted @ 2021-03-17 13:18  ☞@_@  阅读(117)  评论(0编辑  收藏  举报