• 十四天学会C++之第八天:文件操作


    1. 文件的打开和关闭

    • 文件操作的基本概念。
    • 打开文件:使用fstream库打开文件以供读写。
    • 关闭文件:确保文件在使用完毕后正确关闭。

    文件的打开和关闭:C++ 文件操作入门

    在C++编程中,文件操作是一项重要的任务,可以读取和写入数据到文件中。这对于数据的永久性存储和检索至关重要。

    文件操作的基本概念

    在进行文件操作之前,让我们先了解一些基本概念:

    • 文件:文件是数据的持久性存储方式。它可以是文本文件(包含文本信息)或二进制文件(包含二进制数据)。

    • 文件流:在C++中,文件被视为数据流。流是一个抽象的概念,用于表示数据的顺序传递。文件流分为输入流(用于读取文件)和输出流(用于写入文件)。

    打开文件

    要打开文件以供读取或写入,我们需要使用C++的fstream库,它提供了fstream、ifstream和ofstream三个类,分别用于文件的读取、写入和同时读写。

    以下是打开文件的一般步骤:

    1. 包含头文件:首先,您需要包含 头文件以使用文件流类。

    2. 创建文件流对象:根据需求,创建一个输入流对象(ifstream)、输出流对象(ofstream)或输入/输出流对象(fstream)。

    3. 打开文件:使用流对象的 open 方法来打开文件。在打开文件时,需要指定文件的名称和打开模式。例如,要打开一个文本文件以供读取,使用 ifstream 并指定打开模式为 ios::in

    #include 
    
    int main() {
        // 创建输入流对象
        std::ifstream inputFile;
    
        // 打开文件以供读取
        inputFile.open("example.txt", std::ios::in);
    
        if (!inputFile) {
            // 处理文件打开失败的情况
            std::cerr << "无法打开文件" << std::endl;
            return 1;
        }
    
        // 文件已成功打开,可以进行读取操作
    
        // 关闭文件
        inputFile.close();
    
        return 0;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22

    关闭文件

    在文件操作完成后,为了确保文件被正确关闭,我们应该使用流对象的 close 方法关闭文件。这个步骤很重要,因为它确保文件在程序执行后不会被修改或损坏。

    // 关闭文件
    inputFile.close();
    
    • 1
    • 2

    请注意,如果不关闭文件而直接退出程序,文件可能会被操作系统保持打开状态,这可能导致其他问题。

    #include 
    #include 
    
    int main() {
        // 创建输出流对象
        std::ofstream outputFile;
    
        // 打开文件以供写入,如果文件不存在将创建新文件
        outputFile.open("example.txt", std::ios::out);
    
        if (!outputFile) {
            // 处理文件打开失败的情况
            std::cerr << "无法打开文件" << std::endl;
            return 1;
        }
    
        // 写入数据到文件
        outputFile << "这是一个示例文本文件。" << std::endl;
    
        // 关闭文件
        outputFile.close();
    
        return 0;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24

    2. 文件读写

    • 读取文件:使用ifstream类读取文本文件。
    • 写入文件:使用ofstream类将数据写入文本文件。
    • 二进制文件:介绍如何读写二进制文件。

    读取文件

    读取文本文件

    要读取文本文件,我们可以使用ifstream类,它是C++标准库中用于输入文件流的类。以下是读取文本文件的基本步骤:

    1. 包括头文件:首先,您需要包括 头文件以使用文件流类。

    2. 创建ifstream对象:创建一个ifstream对象,并将文件名作为参数传递给其构造函数。

    3. 打开文件:使用ifstream对象的 open 方法打开文件。

    4. 读取数据:使用输入运算符 >> 从文件中读取数据。

    5. 关闭文件:使用ifstream对象的 close 方法关闭文件。

    #include 
    #include 
    #include 
    
    int main() {
        // 创建输入文件流对象
        std::ifstream inputFile;
    
        // 打开文本文件以供读取
        inputFile.open("example.txt", std::ios::in);
    
        if (!inputFile) {
            std::cerr << "无法打开文件" << std::endl;
            return 1;
        }
    
        // 读取文件中的数据
        std::string line;
        while (std::getline(inputFile, line)) {
            std::cout << line << std::endl;
        }
    
        // 关闭文件
        inputFile.close();
    
        return 0;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    写入文件

    要写入数据到文本文件,我们可以使用ofstream类,它是C++标准库中用于输出文件流的类。以下是写入文本文件的基本步骤:

    1. 包括头文件:首先,您需要包括 头文件以使用文件流类。

    2. 创建ofstream对象:创建一个ofstream对象,并将文件名作为参数传递给其构造函数。

    3. 打开文件:使用ofstream对象的 open 方法打开文件。

    4. 写入数据:使用输出运算符 << 向文件中写入数据。

    5. 关闭文件:使用ofstream对象的 close 方法关闭文件。

    #include 
    #include 
    
    int main() {
        // 创建输出文件流对象
        std::ofstream outputFile;
    
        // 打开文本文件以供写入,如果文件不存在将创建新文件
        outputFile.open("example.txt", std::ios::out);
    
        if (!outputFile) {
            std::cerr << "无法打开文件" << std::endl;
            return 1;
        }
    
        // 写入数据到文件
        outputFile << "这是一个示例文本文件。" << std::endl;
    
        // 关闭文件
        outputFile.close();
    
        return 0;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23

    二进制文件

    读写二进制文件,可以使用相同的ifstream和ofstream类,但要注意文件模式。打开二进制文件时,您需要将文件模式设置为std::ios::binary

    #include 
    #include 
    
    int main() {
        // 创建二进制输出文件流对象
        std::ofstream binaryOutputFile;
    
        // 打开二进制文件以供写入,如果文件不存在将创建新文件
        binaryOutputFile.open("binary_data.bin", std::ios::out | std::ios::binary);
    
        if (!binaryOutputFile) {
            std::cerr << "无法打开文件" << std::endl;
            return 1;
        }
    
        // 写入二进制数据到文件
        int data[] = {1, 2, 3, 4, 5};
        binaryOutputFile.write(reinterpret_cast<char*>(data), sizeof(data));
    
        // 关闭文件
        binaryOutputFile.close();
    
        // 创建二进制输入文件流对象
        std::ifstream binaryInputFile;
    
        // 打开二进制文件以供读取
        binaryInputFile.open("binary_data.bin", std::ios::in | std::ios::binary);
    
        if (!binaryInputFile) {
            std::cerr << "无法打开文件" << std::endl;
            return 1;
        }
    
        // 读取二进制数据
        int readData
    
    [5];
        binaryInputFile.read(reinterpret_cast<char*>(readData), sizeof(readData));
    
        // 关闭文件
        binaryInputFile.close();
    
        // 输出读取的数据
        for (int i = 0; i < 5; ++i) {
            std::cout << readData[i] << " ";
        }
        std::cout << std::endl;
    
        return 0;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50

    演示如何将整数数组写入二进制文件,然后再次读取并显示。请注意,使用reinterpret_cast将整数数组的地址转换为char*,以便正确读写二进制数据。

    3. 文本文件和二进制文件的处理

    • 文本文件 vs. 二进制文件:区别和适用场景。
    • 读写文本文件:如何逐行读取和写入文本文件。
    • 读写二进制文件:如何以二进制方式读写文件。

    文本文件 vs. 二进制文件

    文本文件通常包含可读的字符数据,如文本文档、配置文件等。它们使用普通的字符编码(如ASCII或UTF-8)来表示文本内容。文本文件易于阅读和编辑,但不适合存储非文本数据,如图像或音频。

    二进制文件包含的是原始的二进制数据,没有字符编码。它们通常用于存储非文本数据,如图像、音频、视频、数据库文件等。二进制文件可以存储任何类型的数据,但不易于人类阅读或编辑。

    读写文本文件

    读取文本文件
    #include 
    #include 
    #include 
    
    int main() {
        std::ifstream inputFile("textfile.txt"); // 打开文本文件以供读取
    
        if (!inputFile) {
            std::cerr << "无法打开文件" << std::endl;
            return 1;
        }
    
        std::string line;
        while (std::getline(inputFile, line)) { // 逐行读取
            std::cout << line << std::endl; // 处理每行数据
        }
    
        inputFile.close(); // 关闭文件
    
        return 0;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    写入文本文件
    #include 
    #include 
    
    int main() {
        std::ofstream outputFile("output.txt"); // 打开文本文件以供写入
    
        if (!outputFile) {
            std::cerr << "无法打开文件" << std::endl;
            return 1;
        }
    
        outputFile << "写入文本文件的内容" << std::endl; // 写入数据
    
        outputFile.close(); // 关闭文件
    
        return 0;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17

    读写二进制文件

    读写二进制文件需要更小心,必须确保数据以正确的格式进行存储和读取。

    读取二进制文件
    #include 
    #include 
    
    int main() {
        std::ifstream inputFile("binaryfile.bin", std::ios::binary); // 打开二进制文件以供读取
    
        if (!inputFile) {
            std::cerr << "无法打开文件" << std::endl;
            return 1;
        }
    
        int data;
        while (inputFile.read(reinterpret_cast<char*>(&data), sizeof(int))) { // 逐块读取
            std::cout << data << " "; // 处理每个数据块
        }
    
        inputFile.close(); // 关闭文件
    
        return 0;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    写入二进制文件
    #include 
    #include 
    
    int main() {
        std::ofstream outputFile("binaryfile.bin", std::ios::binary); // 打开二进制文件以供写入
    
        if (!outputFile) {
            std::cerr << "无法打开文件" << std::endl;
            return 1;
        }
    
        int data[] = {1, 2, 3, 4, 5};
    
        for (int i = 0; i < 5; ++i) {
            outputFile.write(reinterpret_cast<char*>(&data[i]), sizeof(int)); // 写入数据块
        }
    
        outputFile.close(); // 关闭文件
    
        return 0;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21

    请注意,二进制文件的读写中使用std::ios::binary标志,以确保以二进制模式打开文件。

    4. 示例和练习

    示例1:文本文件读取和写入

    #include 
    #include 
    #include 
    
    int main() {
        // 示例1: 从input.txt读取文本内容,写入output.txt
    
        std::ifstream inputFile("input.txt");
        std::ofstream outputFile("output.txt");
    
        if (!inputFile || !outputFile) {
            std::cerr << "无法打开文件" << std::endl;
            return 1;
        }
    
        std::string line;
        while (std::getline(inputFile, line)) {
            // 处理文本行
            outputFile << line << std::endl;
        }
    
        inputFile.close();
        outputFile.close();
    
        return 0;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26

    示例2:二进制文件读取和写入

    #include 
    #include 
    
    int main() {
        // 示例2: 读取和写入二进制文件
    
        int data[] = {1, 2, 3, 4, 5};
    
        std::ofstream binaryOutputFile("data.bin", std::ios::binary);
        if (!binaryOutputFile) {
            std::cerr << "无法打开文件" << std::endl;
            return 1;
        }
    
        binaryOutputFile.write(reinterpret_cast<char*>(data), sizeof(data));
    
        binaryOutputFile.close();
    
        std::ifstream binaryInputFile("data.bin", std::ios::binary);
        if (!binaryInputFile) {
            std::cerr << "无法打开文件" << std::endl;
            return 1;
        }
    
        int readData[5];
        binaryInputFile.read(reinterpret_cast<char*>(readData), sizeof(readData));
    
        for (int i = 0; i < 5; ++i) {
            std::cout << readData[i] << " ";
        }
    
        binaryInputFile.close();
    
        return 0;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35

    练习题

    问题1:创建一个程序,从用户输入中读取文本,并将其写入名为user_input.txt的文本文件。

    #include 
    #include 
    #include 
    
    int main() {
        std::string userInput;
        
        // 从用户输入读取文本
        std::cout << "请输入文本内容:" << std::endl;
        std::getline(std::cin, userInput);
        
        // 打开文件以写入内容
        std::ofstream outputFile("user_input.txt");
        
        if (!outputFile) {
            std::cerr << "无法打开文件" << std::endl;
            return 1;
        }
        
        // 写入用户输入的文本到文件
        outputFile << userInput << std::endl;
        
        // 关闭文件
        outputFile.close();
        
        std::cout << "文本已写入 user_input.txt 文件。" << std::endl;
        
        return 0;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29

    运行结果:

    在这里插入图片描述

    问题2:创建一个程序,读取名为numbers.txt的文本文件中的数字,计算它们的总和并显示在屏幕上。

    #include 
    #include 
    
    int main() {
        // 打开包含数字的文本文件
        std::ifstream inputFile("numbers.txt");
        
        if (!inputFile) {
            std::cerr << "无法打开文件" << std::endl;
            return 1;
        }
        
        int number;
        int sum = 0;
        
        // 逐行读取数字并计算总和
        while (inputFile >> number) {
            sum += number;
        }
        
        // 关闭文件
        inputFile.close();
        
        // 显示总和
        std::cout << "数字的总和为: " << sum << std::endl;
        
        return 0;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28

    运行结果:

    在这里插入图片描述

    问题3:创建一个程序,使用二进制文件存储学生成绩数据,并编写函数来查找特定学生的分数。

    #include 
    #include 
    #include 
    
    struct Student {
        std::string name;
        int score;
    };
    
    void writeStudentData(const std::string& filename, const Student& student) {
        std::ofstream outputFile(filename, std::ios::binary | std::ios::app);
        
        if (!outputFile) {
            std::cerr << "无法打开文件" << std::endl;
            return;
        }
        
        outputFile.write(reinterpret_cast<const char*>(&student), sizeof(Student));
        outputFile.close();
    }
    
    Student findStudentData(const std::string& filename, const std::string& targetName) {
        Student student;
        
        std::ifstream inputFile(filename, std::ios::binary);
        
        if (!inputFile) {
            std::cerr << "无法打开文件" << std::endl;
            return student;
        }
        
        while (inputFile.read(reinterpret_cast<char*>(&student), sizeof(Student))) {
            if (student.name == targetName) {
                inputFile.close();
                return student;
            }
        }
        
        inputFile.close();
        student.name = "未找到";
        student.score = -1;
        return student;
    }
    
    int main() {
        // 写入学生数据到二进制文件
        Student student1 = { "Alice", 90 };
        Student student2 = { "Bob", 85 };
        writeStudentData("student_data.bin", student1);
        writeStudentData("student_data.bin", student2);
    
        // 查找特定学生的分数
        std::string targetName = "Alice";
        Student foundStudent = findStudentData("student_data.bin", targetName);
    
        if (foundStudent.name == "未找到") {
            std::cout << "找不到学生:" << targetName << std::endl;
        } else {
            std::cout << "学生姓名:" << foundStudent.name << ",分数:" << foundStudent.score << std::endl;
        }
    
        return 0;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63

    运行结果:

    在这里插入图片描述

    问题4:创建一个程序,将两个文本文件合并成一个新文件。

    #include 
    #include 
    #include 
    
    int main() {
        // 打开第一个文本文件以读取内容
        std::ifstream inputFile1("file1.txt");
        
        if (!inputFile1) {
            std::cerr << "无法打开文件1" << std::endl;
            return 1;
        }
    
        // 打开第二个文本文件
    
        std::ifstream inputFile2("file2.txt");
    
        if (!inputFile2) {
            std::cerr << "无法打开文件2" << std::endl;
            return 1;
        }
    
        // 创建新文件以写入合并内容
        std::ofstream outputFile("merged_file.txt");
    
        if (!outputFile) {
            std::cerr << "无法创建新文件" << std::endl;
            return 1;
        }
    
        // 从文件1读取并写入到新文件
        std::string line;
        while (std::getline(inputFile1, line)) {
            outputFile << line << std::endl;
        }
    
        // 从文件2读取并写入到新文件
        while (std::getline(inputFile2, line)) {
            outputFile << line << std::endl;
        }
    
        // 关闭文件
        inputFile1.close();
        inputFile2.close();
        outputFile.close();
    
        std::cout << "文件已成功合并为 merged_file.txt" << std::endl;
    
        return 0;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50

    运行结果:

    在这里插入图片描述

  • 相关阅读:
    欧盟仍在阻止社交媒体用户的数据传输
    JAVA麦克风实时录音调用听写并存储音频到本地
    Linux使用YUM安装程序准备
    Redis事务相关源码探究
    二>jvm到底是什么?有什么作用?工作机制如何?
    vue多条件查询
    牛客多校2 - Link with Bracket Sequence I(括号序列,三维DP)
    阿里拆了中台,中台还有未来吗?
    【操作系统】模块四:进程和线程
    【什么是摆线减速器?设计、3D 打印和测试】
  • 原文地址:https://blog.csdn.net/m0_53918860/article/details/133974115