相关疑难解决方法(0)

C++从文件流中读取unsigned char

我想从二进制文件中读取无符号字节.所以我写了下面的代码.

#include <iostream>
#include <fstream>
#include <vector>
#include <istream>

std::string filename("file");
size_t bytesAvailable = 128;
size_t toRead = 128;

std::basic_ifstream<unsigned char> inf(filename.c_str(), std::ios_base::in | std::ios_base::binary) ;
if (inF.good())
{
    std::vector<unsigned char> mDataBuffer;
    mDataBuffer.resize(bytesAvailable) ;
    inF.read(&mDataBuffer[0], toRead) ;
    size_t counted = inF.gcount() ;
}
Run Code Online (Sandbox Code Playgroud)

这导致读取始终为0字节,如计数变量所示.

网上似乎有一些引用说我需要设置语言环境才能使其正常工作.如何做到这一点对我来说并不清楚.

相同的代码使用数据类型'char'而不是'unsigned char'

上面使用unsigned char的代码似乎可以在Windows上运行,但无法在colinux Fedora 2.6.22.18中运行.

为了让它适用于linux,我需要做些什么?

c++ file-io stream ifstream

12
推荐指数
2
解决办法
5万
查看次数

为什么这个专门用于basic_ifstream模板的char_traits <uint8_t>和codecvt <uint8_t>会抛出std :: bad_cast?

目前 已经 问题在这里问#1 为什么 basic_fstream<uint8_t>不工作.答案说这char_traits只是专门用于charwchar_t(加上char16_t,char32_t在C++ 11中),你应该坚持basic_fstream<char>阅读二进制数据并在需要时投射它.

好吧,这还不够好!:)

没有任何答案(我能找到)说明如何专门化char_traits<uint8_t>和使用basic_fstream模板,或者甚至可能.所以我想我会尝试自己实现它.

在Windows 7 64位上使用Visual Studio Express 2013 RC并在Kubuntu GNU/Linux 13.04 64位上使用g ++ - 4.7时,以下编译没有错误.但是它会在运行时抛出std :: bad_cast异常.我没有访问clang ++和libc ++来测试这个组合.

#include <cinttypes>
#include <cstring>

#include <algorithm>
#include <fstream>
#include <iostream>
#include <locale>

#ifdef _WIN32
    #define constexpr
    #define NOEXCEPT throw()
#else
    #define NOEXCEPT noexcept
#endif

// Change this to char and it works.
using byte_type …
Run Code Online (Sandbox Code Playgroud)

c++ g++ visual-studio c++11 char-traits

12
推荐指数
1
解决办法
1971
查看次数

标签 统计

c++ ×2

c++11 ×1

char-traits ×1

file-io ×1

g++ ×1

ifstream ×1

stream ×1

visual-studio ×1