使用 C++ 逐行读写文件

C++C++Beginner
立即练习

💡 本教程由 AI 辅助翻译自英文原版。如需查看原文,您可以 切换至英文原版

介绍

在本实验中,你将学习如何使用 C++ 编程语言逐行读取和写入文件。你将创建一个文件,向其中写入内容,然后逐行读取其内容。


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL cpp(("`C++`")) -.-> cpp/ControlFlowGroup(["`Control Flow`"]) cpp(("`C++`")) -.-> cpp/OOPGroup(["`OOP`"]) cpp(("`C++`")) -.-> cpp/IOandFileHandlingGroup(["`I/O and File Handling`"]) cpp/ControlFlowGroup -.-> cpp/while_loop("`While Loop`") cpp/OOPGroup -.-> cpp/classes_objects("`Classes/Objects`") cpp/OOPGroup -.-> cpp/class_methods("`Class Methods`") cpp/IOandFileHandlingGroup -.-> cpp/output("`Output`") cpp/IOandFileHandlingGroup -.-> cpp/user_input("`User Input`") cpp/IOandFileHandlingGroup -.-> cpp/files("`Files`") subgraph Lab Skills cpp/while_loop -.-> lab-96213{{"`使用 C++ 逐行读写文件`"}} cpp/classes_objects -.-> lab-96213{{"`使用 C++ 逐行读写文件`"}} cpp/class_methods -.-> lab-96213{{"`使用 C++ 逐行读写文件`"}} cpp/output -.-> lab-96213{{"`使用 C++ 逐行读写文件`"}} cpp/user_input -.-> lab-96213{{"`使用 C++ 逐行读写文件`"}} cpp/files -.-> lab-96213{{"`使用 C++ 逐行读写文件`"}} end

创建并打开文件

~/project 目录下创建一个名为 file_io.cpp 的 C++ 文件。在这一步中,你将创建并打开一个名为 example.txt 的文件。

#include <fstream>

int main() {
    // 创建并打开文件
    std::ofstream ofs;
    ofs.open("example.txt", std::ofstream::out | std::ofstream::trunc);
    ofs.close();
    return 0;
}

解释:

  • ofstream 是一个用于写入文件的类。
  • ofsofstream 类的一个对象。
  • open() 方法用于创建并打开文件。
  • open() 方法中,第一个参数是要创建的文件名,第二个参数指定文件的打开模式。在这里,out 表示文件以写入模式打开,trunc 表示如果文件已存在则将其截断。

写入文件

在这一步中,你将向文件 example.txt 中写入内容。

#include <fstream>
#include <iostream>
#include <string>

int main() {
    std::ofstream ofs;
    ofs.open("example.txt", std::ofstream::out | std::ofstream::trunc);
    if (ofs.is_open()) {
        std::cout << "Enter text to write to the file (Enter empty line to exit):" << std::endl;
        std::string line;
        do {
            std::getline(std::cin, line);
            if (line.length()) {
                ofs << line << std::endl;
            }
        } while (line.length());
        ofs.close();
    } else {
        std::cerr << "Error in opening the file" << std::endl;
    }
    return 0;
}

解释:

  • std::cout 用于在控制台上显示一条消息,提示用户输入要写入文件的文本。
  • std::getline() 用于逐行读取用户输入并将其存储在 line 变量中。
  • if (line.length()) 用于检查用户是否输入了任何文本。如果用户没有输入任何文本,则循环将退出。
  • ofs << line << std::endl; 用于将用户输入写入文件,并在每行末尾添加换行符。
  • std::cerr 用于在文件无法打开时在控制台上显示错误消息。

要运行此程序,请进入 ~/project 目录并运行以下命令:

g++ file_io.cpp -o file_io && ./file_io

此程序将提示用户输入要写入文件的文本,然后将用户输入写入文件。

读取文件

在这一步中,你将读取 example.txt 文件的内容。

#include <fstream>
#include <iostream>
#include <string>

int main() {
    std::ifstream ifs;
    ifs.open("example.txt");
    if (ifs.is_open()) {
        std::cout << "Contents of the file:" << std::endl;
        std::string line;
        while (std::getline(ifs, line)) {
            std::cout << line << std::endl;
        }
        ifs.close();
    } else {
        std::cerr << "Error in opening the file" << std::endl;
    }
    return 0;
}

解释:

  • std::ifstream 是一个用于读取文件的类。
  • ifsifstream 类的一个对象。
  • open() 方法用于打开一个已存在的文件。
  • open() 方法中,参数是要打开的文件的名称。
  • std::cout 用于在控制台上显示一条消息,表示正在显示文件的内容。
  • std::getline() 用于逐行读取文件内容并将其存储在 line 变量中。
  • std::cout << line << std::endl; 用于在控制台上逐行显示文件内容。

要运行此程序,请进入 ~/project 目录并运行以下命令:

g++ file_io.cpp -o file_io && ./file_io

此程序将在控制台上显示 example.txt 文件的内容。

总结

在本实验中,你学习了如何使用 C++ 编程语言创建、写入和读取文件。你学习了如何使用 ofstreamifstream 类分别向文件写入内容和从文件读取内容。你还学习了如何使用 open() 方法创建并打开文件,以及如何使用 getline() 方法逐行读取文件内容。

您可能感兴趣的其他 C++ 教程