#include <iostream>
#include <fstream>
#include <string>
std::string fileToString(const std::string& filePath) {
// 打开文件
std::ifstream file(filePath, std::ios::binary);
// 检查文件是否成功打开
if (!file.is_open()) {
std::cerr << "Failed to open file: " << filePath << std::endl;
return "";
}
// 使用 std::string 的构造函数从文件流中读取内容
std::string content((std::istreambuf_iterator<char>(file)),
std::istreambuf_iterator<char>());
// 关闭文件
file.close();
return content;
}
int main() {
const std::string filePath = "path/to/your/file"; // 替换为你的文件路径
std::string fileContent = readFile(filePath);
if (!fileContent.empty()) {
std::cout << "Read " << fileContent.size() << " bytes from the file." << std::endl;
// 可以输出内容(如果内容不是太大)
// std::cout << fileContent; // 不推荐输出大型文件内容
} else {
std::cerr << "Failed to read file content." << std::endl;
}
return 0;
}
读取一个文件,将文件中所有内容存入一个std::string
于 2024-10-18 14:27:18 首次发布
5926

被折叠的 条评论
为什么被折叠?



