文件操作

91 阅读1分钟

程序运行时产生的数据都属于临时数据,程序一旦运行结束都会被释放

通过文件可以将数据持久化

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

文件类型分为两种:

  1. 文本文件 - 文件以文本的ASCII码形式存储在计算机中
  2. 二进制文件 - 文件以文本的二进制形式存储在计算机中,用户一般不能直接读懂它们

操作文件的三大类:

  1. ofstream:写操作
  2. ifstream: 读操作
  3. fstream : 读写操作

文本文件

写文件

写文件步骤如下:

  1. 包含头文件

    #include

  2. 创建流对象

    ofstream ofs;

  3. 打开文件

    ofs.open(“文件路径”,打开方式);

  4. 写数据

    ofs << “写入的数据”;

  5. 关闭文件

    ofs.close();

文件打开方式:

打开方式解释
ios::in为读文件而打开文件
ios::out为写文件而打开文件
ios::ate初始位置:文件尾
ios::app追加方式写文件
ios::trunc如果文件存在先删除,再创建
ios::binary二进制方式

注意:  文件打开方式可以配合使用,利用|操作符

**例如:**用二进制方式写文件 ios::binary | ios:: out

#include <fstream>


void file_reader(std::string filename){
    std::fstream file;
    file.open(filename, std::ios::in);
    if(file.is_open()){
        // file reader method 1
        std::string line;
        while(getline(file, line)){
            std::cout << line << std::endl;
        }
        // file reader method 2
        char buff[1024] = {0};
        while(file >> buff){
            std::cout << buff << std::endl;
        }

        // file reader method 3
        char buff[1024] = {0};
        while(file.getline(buff, sizeof(buff))){
            std::cout << buff << std::endl;
        }
        // file reader method 4
        char c;
        while((c = file.get()) != EOF){
            std::cout << c;
        }
        file.close();
    }
}

int main(){
    std::string filename = "testing.txt";
    file_reader(filename);
    return 0;
}