C++,读取文件内容

需要包含的头文件:

#include <iostream>
#include <sstream>
#include <fstream>

函数如下:

std::string LoadFile(const char* filepath)
{
    std::string content;
    std::ifstream file_stream;

    file_stream.exceptions(std::ifstream::failbit | std::ifstream::badbit);

	try
	{
		file_stream.open(filepath);
        std::stringstream string_stream;
        string_stream << file_stream.rdbuf();
        file_stream.close();
        content = string_stream.str();
	}
	catch(const std::exception& e)
	{
		std::cerr << e.what() << '\n';
	}
	
    return content;
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
可以使用C++中的文件流来读取文件内容。下面是一个简单的例子: ```c++ #include <iostream> #include <fstream> #include <string> using namespace std; int main() { ifstream myfile("example.txt"); // 创建一个文件输入流对象并打开文件 string line; if (myfile.is_open()) { // 判断文件是否成功打开 while (getline(myfile, line)) { // 从文件中逐行读取内容 cout << line << endl; // 输出每一行的内容 } myfile.close(); // 关闭文件 } else { cout << "Unable to open file." << endl; } return 0; } ``` 上述代码将打开名为example.txt的文件,并逐行输出其内容。在代码中,我们使用了`ifstream`类来创建一个文件输入流对象。我们将文件名作为参数传递给构造函数,该构造函数将打开文件并返回一个可以用于读取文件内容的流对象。在代码的主循环中,我们使用`getline`函数逐行读取文件内容,并将其存储在一个字符串变量`line`中。最后,我们将每一行的内容输出到控制台中,并在循环结束后关闭文件流对象。 如果您想一次性读取整个文件内容,可以使用以下代码: ```c++ #include <iostream> #include <fstream> #include <string> using namespace std; int main() { ifstream myfile("example.txt"); // 创建一个文件输入流对象并打开文件 string content; if (myfile.is_open()) { // 判断文件是否成功打开 // 获取文件长度 myfile.seekg(0, ios::end); int length = myfile.tellg(); myfile.seekg(0, ios::beg); // 分配足够的内存来存储文件内容 content.resize(length); // 从文件读取内容 myfile.read(&content[0], length); myfile.close(); // 关闭文件 } else { cout << "Unable to open file." << endl; } cout << content << endl; // 输出文件内容 return 0; } ``` 在上述代码中,我们首先创建了一个`ifstream`对象并打开了文件。然后,我们使用`seekg`和`tellg`函数获取文件长度,并分配足够的内存来存储文件内容。最后,我们使用`read`函数从文件读取内容,并将其存储在字符串变量`content`中。最后,我们将整个文件内容输出到控制台中,并在循环结束后关闭文件流对象。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值