gpt4 book ai didi

c++ - wifstream 中的 seekg 和 imbue 工作错误

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:11:51 29 4
gpt4 key购买 nike

我有一个如下的文件:

$ xxd 1line
0000000: 3939 ba2f 6f20 6f66 0d0a 99./o of..

我想用 C++ 阅读这一行:

#include <codecvt>
#include <iostream>
#include <locale>
#include <fstream>
#include <string>

int main(int argc, char** argv) {
std::wifstream wss(argv[1], std::ios::binary);
wss.seekg(std::ios_base::end);
const auto fileSize = wss.tellg();
wss.seekg(std::ios_base::beg);

// std::locale utf8_locale(wss.getloc(), new std::codecvt_utf8<wchar_t, 0x10FFFF, std::consume_header>);
// wss.imbue(utf8_locale);

std::wstring wline;
std::getline(wss, wline);

std::cout << "filelen: " << fileSize << std::endl;
std::cout << "strlen: " << wline.size() << std::endl;
std::wcout << "str: " << wline << std::endl;

return 0;
}

我用下面的方式编译它:

$ g++ -std=c++11 imbue_issue.cpp

第一件事:wss.seekg(std::ios_base::end) 似乎没有移动文件末尾的文件位置:

$ ./a.out 1line
filelen: 2
strlen: 9
str: 99?/o of

第二件事是当取消注释与区域设置相关的行时,getline 只读取 2 个字符:

$ ./a.out 1line
filelen: 2
strlen: 2
str: 99

我的编译器:

$ g++ --version
Configured with: --prefix=/Applications/Xcode.app/Contents/Developer/usr --with-gxx-include-dir=/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.11.sdk/usr/include/c++/4.2.1
Apple LLVM version 7.3.0 (clang-703.0.31)
Target: x86_64-apple-darwin15.6.0
Thread model: posix
InstalledDir: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin

有谁知道此文件出现上述问题的原因是什么?

最佳答案

问题是你如何调用the seekg function .当您使用一个参数调用它时,它被用作从一开始的绝对位置,您将寻找 std::ios::end 具有的任何值,这会发生在您的情况下为 2

相反,您应该使用双参数重载:

wss.seekg(0, std::ios_base::end);  // Seek to offset 0 from the end

使用宽字符类型读取文件仍然会有问题,因为内容似乎不是那样。 UTF-8 是一种多字节字符编码。

关于c++ - wifstream 中的 seekg 和 imbue 工作错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40102998/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com