Reputation: 225
I am facing an issue when reading the file contents in C++.
I have a text file with content "Password=(|OBFUSCATED:A;Q=K?[LNQGMXNLd282>;3Cl]*I(n7$:OBFUSCATED|)".
when i try to read the file and save its content to wstring, complete file contents are not read but instead only "Password=(|OBFUSCATED:" is read into wstring variable.
Codesnippet is :
std::wifstream input1(path);
std::wstring content((std::istreambuf_iterator<wchar_t>(input1)),
(std::istreambuf_iterator<wchar_t>()));
Need help in reading the file contents.
Thanks in Advance!!
LATHA
Upvotes: 2
Views: 2132
Reputation: 1
Pulling info from several places... This should be the fastest and best way:
#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;
}
Upvotes: 0
Reputation: 392921
Out on a limb, add binary
to the open flags:
std::wifstream input1(path, std::ios::binary);
std::wstring content((std::istreambuf_iterator<wchar_t>(input1)),
{});
Upvotes: 3