📜  如何从文件加载 C++ (1)

📅  最后修改于: 2023-12-03 15:37:56.201000             🧑  作者: Mango

如何从文件加载 C++

在 C++ 中,我们可以使用文件作为输入源或输出目标。在这篇文章中,我们将学习如何从文件中加载 C++ 代码。

读取文件

下面是 C++ 中读取文件的常见方法:

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

using namespace std;

int main() {
    string line;
    ifstream file("input.txt");
    if (file.is_open()) {
        while (getline(file, line)) {
            // 处理每一行数据
            cout << line << endl;
        }
        file.close();
    } else {
        cout << "无法打开文件" << endl;
    }
    return 0;
}

上面的代码中,我们打开了一个名为 "input.txt" 的文件。在 while 循环中,我们使用 getline() 函数从文件中读取每一行数据,并将其输出到控制台上。

写入文件

下面是 C++ 中写入文件的常见方法:

#include <iostream>
#include <fstream>

using namespace std;

int main() {
    ofstream file("output.txt");
    if (file.is_open()) {
        file << "写入文件" << endl;
        file.close();
    } else {
        cout << "无法打开文件" << endl;
    }
    return 0;
}

上面的代码中,我们打开了一个名为 "output.txt" 的文件。然后,我们使用 << 运算符将文本写入文件中,并使用 close() 函数关闭文件。

总结

在本文中,我们介绍了如何在 C++ 中从文件中读取和写入数据。在实际编程中,您可能需要更复杂的文件操作,比如二进制文件的读写等。但本文中的方法足以满足基本的文件操作需求。

参考资料