首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >C++:将文件内容读入wstring

C++:将文件内容读入wstring
EN

Stack Overflow用户
提问于 2015-11-05 09:20:38
回答 2查看 1.4K关注 0票数 2

在C++中读取文件内容时,我面临一个问题。

我有一个包含内容"Password=(|OBFUSCATED:A;Q=K?LNQGMXNLd282>;3Cl*I(n7$:OBFUSCATED|)".的文本文件

当我试图读取该文件并将其内容保存到wstring时,不读取完整的文件内容,而是只将“Password=(困惑:”)读入wstring变量中。

Codesnippet是:

代码语言:javascript
运行
复制
std::wifstream input1(path);
std::wstring content((std::istreambuf_iterator<wchar_t>(input1)),
        (std::istreambuf_iterator<wchar_t>()));

在读取文件内容时需要帮助。

提前谢谢!!

拉萨

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2015-11-05 09:30:13

在一个分支上,将binary添加到打开的标志中:

代码语言:javascript
运行
复制
std::wifstream input1(path, std::ios::binary);
std::wstring content((std::istreambuf_iterator<wchar_t>(input1)),
    {});
票数 3
EN

Stack Overflow用户

发布于 2022-04-10 02:26:24

从几个地方收集信息..。这应该是最快和最好的方法:

代码语言:javascript
运行
复制
#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;
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/33540662

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档