在C++中读取文件内容时,我面临一个问题。
我有一个包含内容"Password=(|OBFUSCATED:A;Q=K?LNQGMXNLd282>;3Cl*I(n7$:OBFUSCATED|)".的文本文件
当我试图读取该文件并将其内容保存到wstring时,不读取完整的文件内容,而是只将“Password=(困惑:”)读入wstring变量中。
Codesnippet是:
std::wifstream input1(path);
std::wstring content((std::istreambuf_iterator<wchar_t>(input1)),
(std::istreambuf_iterator<wchar_t>()));
在读取文件内容时需要帮助。
提前谢谢!!
拉萨
发布于 2015-11-05 09:30:13
在一个分支上,将binary
添加到打开的标志中:
std::wifstream input1(path, std::ios::binary);
std::wstring content((std::istreambuf_iterator<wchar_t>(input1)),
{});
发布于 2022-04-10 02:26:24
从几个地方收集信息..。这应该是最快和最好的方法:
#include <filesystem>
#include <fstream>
#include <string>
//Returns true if successful.
bool readInFile(std::string pathString)
{
//Make sure the file exists and is an actual file.
if (!std::filesystem::is_regular_file(pathString))
{
return false;
}
//Convert relative path to absolute path.
pathString = std::filesystem::weakly_canonical(pathString);
//Open the file for reading (binary is fastest).
std::wifstream in(pathString, std::ios::binary);
//Make sure the file opened.
if (!in)
{
return false;
}
//Wide string to store the file's contents.
std::wstring fileContents;
//Jump to the end of the file to determine the file size.
in.seekg(0, std::ios::end);
//Resize the wide string to be able to fit the entire file (Note: Do not use reserve()!).
fileContents.resize(in.tellg());
//Go back to the beginning of the file to start reading.
in.seekg(0, std::ios::beg);
//Read the entire file's contents into the wide string.
in.read(fileContents.data(), fileContents.size());
//Close the file.
in.close();
//Do whatever you want with the file contents.
std::wcout << fileContents << L" " << fileContents.size();
return true;
}
https://stackoverflow.com/questions/33540662
复制相似问题