详细介绍c++中的文件处理

C++ 中的文件处理是通过标准库中的 <fstream> 头文件提供的类来实现的。文件处理主要包括文件的打开、读取、写入和关闭等操作。C++ 提供了三个主要的类来处理文件:

  1. std::ifstream:用于从文件中读取数据(输入文件流)。

  2. std::ofstream:用于向文件中写入数据(输出文件流)。

  3. std::fstream:既可以用于读取文件,也可以用于写入文件(输入输出文件流)。

这些类都继承自 std::istreamstd::ostream,因此可以使用类似于 std::cinstd::cout 的操作来处理文件。


文件处理的基本步骤

  1. 打开文件 :使用 open() 函数或构造函数打开文件。

  2. 检查文件是否成功打开 :使用 is_open() 函数检查文件是否成功打开。

  3. 读取或写入文件 :使用流操作符(>><<)或成员函数(如 get()getline()read()write())进行文件操作。

  4. 关闭文件 :使用 close() 函数关闭文件。

文件打开模式

在打开文件时,可以指定文件的打开模式。常用的文件打开模式如下:

模式标志 描述
std::ios::in 打开文件用于读取(默认模式,适用于 ifstream)。
std::ios::out 打开文件用于写入(默认模式,适用于 ofstream)。
std::ios::app 追加模式,所有写入操作都在文件末尾进行。
std::ios::ate 打开文件后,将文件指针定位到文件末尾。
std::ios::trunc 如果文件已存在,则清空文件内容(默认模式,适用于 ofstream)。
std::ios::binary 以二进制模式打开文件(默认是文本模式)。

这些模式可以通过按位或操作符 | 组合使用。

文件读取和写入

1. 使用 std::ifstream 读取文件

cpp 复制代码
#include <iostream>
#include <fstream>
#include <string>

int main() {
    std::ifstream inputFile("example.txt"); // 打开文件
    if (!inputFile.is_open()) {
        std::cerr << "Failed to open the file!" << std::endl;
        return 1;
    }

    std::string line;
    while (std::getline(inputFile, line)) { // 逐行读取文件
        std::cout << line << std::endl;
    }

    inputFile.close(); // 关闭文件
    return 0;
}

2. 使用 std::ofstream 写入文件

cpp 复制代码
#include <iostream>
#include <fstream>

int main() {
    std::ofstream outputFile("example.txt", std::ios::out | std::ios::trunc); // 打开文件并清空内容
    if (!outputFile.is_open()) {
        std::cerr << "Failed to open the file!" << std::endl;
        return 1;
    }

    outputFile << "Hello, World!" << std::endl; // 写入数据
    outputFile << "This is a test file." << std::endl;

    outputFile.close(); // 关闭文件
    return 0;
}

3. 使用 std::fstream 进行读写

cpp 复制代码
#include <iostream>
#include <fstream>
#include <string>

int main() {
    std::fstream file("example.txt", std::ios::in | std::ios::out | std::ios::app); // 打开文件并追加
    if (!file.is_open()) {
        std::cerr << "Failed to open the file!" << std::endl;
        return 1;
    }

    // 写入数据
    file << "Appending a new line." << std::endl;

    // 读取数据
    file.seekg(0); // 将文件指针移动到文件开头
    std::string line;
    while (std::getline(file, line)) {
        std::cout << line << std::endl;
    }

    file.close(); // 关闭文件
    return 0;
}

二进制文件处理

二进制文件处理与文本文件处理类似,但需要使用 std::ios::binary 模式打开文件,并使用 read()write() 函数进行读写。

1. 写入二进制文件

cpp 复制代码
#include <iostream>
#include <fstream>

struct Data {
    int id;
    char name[20];
};

int main() {
    std::ofstream outputFile("data.bin", std::ios::out | std::ios::binary);
    if (!outputFile.is_open()) {
        std::cerr << "Failed to open the file!" << std::endl;
        return 1;
    }

    Data data = {1, "John Doe"};
    outputFile.write(reinterpret_cast<char*>(&data), sizeof(data)); // 写入二进制数据

    outputFile.close();
    return 0;
}

2. 读取二进制文件

cpp 复制代码
#include <iostream>
#include <fstream>

struct Data {
    int id;
    char name[20];
};

int main() {
    std::ifstream inputFile("data.bin", std::ios::in | std::ios::binary);
    if (!inputFile.is_open()) {
        std::cerr << "Failed to open the file!" << std::endl;
        return 1;
    }

    Data data;
    inputFile.read(reinterpret_cast<char*>(&data), sizeof(data)); // 读取二进制数据

    std::cout << "ID: " << data.id << ", Name: " << data.name << std::endl;

    inputFile.close();
    return 0;
}

文件指针操作

文件指针用于定位文件中的读写位置。C++ 提供了以下函数来操作文件指针:

1.tellg():返回输入文件指针的当前位置。

2.tellp():返回输出文件指针的当前位置。

3.seekg(offset, direction):移动输入文件指针。

4.seekp(offset, direction):移动输出文件指针。

其中,direction 可以是:

1.std::ios::beg:文件开头。

2.std::ios::cur:当前位置。

3.std::ios::end:文件末尾。

cpp 复制代码
#include <iostream>
#include <fstream>

int main() {
    std::fstream file("example.txt", std::ios::in | std::ios::out);
    if (!file.is_open()) {
        std::cerr << "Failed to open the file!" << std::endl;
        return 1;
    }

    file << "Hello, World!" << std::endl;

    file.seekg(0); // 将文件指针移动到开头
    std::string line;
    std::getline(file, line);
    std::cout << "First line: " << line << std::endl;

    file.close();
    return 0;
}

总结

C++ 的文件处理功能非常强大,能够满足大多数文件操作需求。通过 ifstreamofstreamfstream,可以轻松实现文件的读取、写入和追加操作。对于二进制文件,可以使用 read()write() 函数进行高效的数据处理。文件指针操作则提供了对文件内容的精确控制。

相关推荐
0wioiw02 分钟前
C++基础(VScode环境安装)
开发语言·c++
hhw1991123 分钟前
c#面试题整理7
开发语言·c#
Java&Develop8 分钟前
java项目springboot 项目启动不了解决方案
java·开发语言·spring boot
qq_2573795913 分钟前
python基础-字符串速查笔记
开发语言·笔记·python
念故思旧14 分钟前
【最长递增子序列】【LeetCode算法】【c++】【动态规划】
c++·算法·leetcode·动态规划
一条闲鱼_mytube18 分钟前
golang recover错误
开发语言·后端·golang
Sean_summer18 分钟前
python语言总结(持续更新)
开发语言·python
虽千万人 吾往矣18 分钟前
golang算法快慢指针
开发语言·算法·golang
竹等寒22 分钟前
Go红队开发—web网络编程
开发语言·前端·网络·安全·web安全·golang
界面开发小八哥29 分钟前
数据可视化图表库LightningChart JS 全新发布v7.0——提高视觉质量
开发语言·javascript·信息可视化·图表·lightningchart