它可能看起来很简单,但我要找到它不起作用的原因。我有两个功能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;
}
但是当我使用ifstream
orofstream
和类型转换为 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;
}
工作正常。有没有办法为 unsigned char 指针类型制作basic_ifstream<unsigned char>
或正常工作,或者在使用或使用basic_ofstream<unsigned char>
时避免类型转换?ifstream
ofstream