文件(SETTINGS.TXT)的端部不读新行的文件内容进行解析:未定义字符,而在文件
FULLSCREEN=On
V_SYNC=On [no "\n" at the end of file]
万一没有ENTER“\ n”个输出是:
MapKey= FULLSCREEN MapValue= On
MapKey= V_SYNC MapValue= Onřřřř
随着ENTER“\ n”的文件输出的到底是正确的(没有“RRRR”):
MapKey= FULLSCREEN MapValue= On
MapKey= V_SYNC MapValue= On
如何更改程序而不ADDI工作在文件的末尾添加新行?代码:
#include<iostream>
#include<fstream>
#include<sstream>
#include<vector>
#include<cstdint>
#include<memory>
int main()
{
std::vector<std::pair<std::string, std::string>> container;
std::ifstream containerFile("settings.txt", std::ifstream::binary);
containerFile.seekg(0, containerFile.end);
std::uint64_t fileSize = containerFile.tellg();
containerFile.seekg(0);
std::unique_ptr<char> fileBuffer(new char[fileSize]);
containerFile.read(fileBuffer.get(), fileSize);
std::istringstream fileContent(fileBuffer.get());
std::string fileLine;
while (std::getline(fileContent, fileLine))
{
std::istringstream bufferLine(fileLine);
std::string option;
if (std::getline(bufferLine, option, '='))
{
std::string value;
if (std::getline(bufferLine, value))
{
container.emplace_back(make_pair(option, value));
}
}
}
for (auto &element : container)
{
std::cout << "MapKey= " << element.first << " MapValue= " << element.second << std::endl;
}
containerFile.close();
}
'std :: istringstream fileContent(fileBuffer.get());' - 一个不正确的以null结尾的char缓冲区被转换为std :: string。有很多方法可以解决这个问题,比如显式构造字符串的长度:'std :: istringstream fileContent(std :: string(fileBuffer.get(),fileSize));' –
如果这是一个Windows系统,并且如果这是一个标准的文本文件,使用'std :: ifstream :: binary'读取会在每个换行符之前保留额外的回车符:('“\ r \ n”'),这也可能导致解析问题。 –