使用filestream从/向文件读取/写入unsigned char数组

时间:2013-11-11 17:04:37

标签: c++ file-io filestream unsigned-char

看起来很简单,但我找不到它不起作用的原因。我有两个函数read_file_cpp()& write_file_cpp()read_file_cpp()读取文件并将其存储在unsigned char指针& write_file_cpp()将unsigned char指针的数据写回文件。

但是当我使用basic_ifstream<unsigned char>basic_ofstream<unsigned char>文件流时,这两个函数都无法读/写数据,unsigned char指针的内容保持不变。以下是代码片段:

int read_file_cpp(unsigned char *pInData,
                  int in_len,
                  string file_name) {

    basic_ifstream<unsigned char> file_stream;

    file_stream.open(file_name.c_str(),ios::in | ios::binary);

    if (!file_stream.is_open()) {
        cout << stderr << "Can't open input file !\n";
        exit(1);
    }
    else{
        file_stream.read(pInData,in_len);
    }

    file_stream.close();

    return 0;
}

int write_file_cpp(string file_name,
                   unsigned char *pOutData,
                   int out_len) {

basic_ofstream<unsigned char> file_stream;

file_stream.open(file_name.c_str(),ios::out | ios::binary | ios::trunc);

if (!file_stream.is_open()) {
    cout << stderr << "Can't open output file !\n";
    exit(1);
}
else{
    file_stream.write(pOutData,out_len);
}

file_stream.close();

return 0;
}

但是当我使用ifstreamofstream和类型转换为char指针时,这两个函数都能正常工作,即

int read_file_cpp(unsigned char *pInData,
                  int in_len,
                  string file_name) {

    ifstream file_stream;

    file_stream.open(file_name.c_str(),ios::in | ios::binary);

    if (!file_stream.is_open()) {
        cout << stderr << "Can't open input file !\n";
        exit(1);
    }
    else{
        file_stream.read((char *)pInData,in_len);
    }

    file_stream.close();

    return 0;
}

工作正常。有没有办法让basic_ifstream<unsigned char>basic_ofstream<unsigned char>正确使用无符号字符指针类型,或者在使用ifstreamofstream时避免类型转换?

1 个答案:

答案 0 :(得分:1)

类型转换是必需的,因为unsigned char没有istream或ostream方法。

顺便说一下,在你的函数中,你可能想要返回写入或读取的实际字节数(否则它是多余的,因为它被传入。)

使用std::istream::gcount来读取字符。