我正在尝试使用 fstream 读取一个 long 数组并将其写入二进制文件。我将数组定义如下:
#define MAX_SUB_BUCKETS 27
unsigned long origin[MAX_SUB_BUCKETS];
unsigned long nextAvail[MAX_SUB_BUCKETS];
fstream fh;
我打开文件并尝试以下操作:
fh.open(fileName.c_str(), fstream::in | fstream::out | fstream::binary);
if (fh.fail()) {
// create new file here and write all zeroes to it (plus header)
} else {
fh.seekg (0, ios::beg);
for (i=0;i<MAX_SUB_BUCKETS;i++) {
fh.read(origin[i],sizeof(long));
}
for (i=0;i<MAX_SUB_BUCKETS;i++) {
fh.read (nextAvail[i],sizeof(long));
}
}
编译器抱怨以下错误:
tld.hh:39: error: invalid conversion from 'long unsigned int' to 'char*'
tld.hh:39: error: initializing argument 1 of 'std::basic_istream<_CharT, _Traits>& std::basic_istream<_CharT, _Traits>::read(_CharT*, std::streamsize) [with _CharT = char, _Traits = std::char_traits<char>]'
tld.hh:42: error: invalid conversion from 'long unsigned int' to 'char*'
tld.hh:42: error: initializing argument 1 of 'std::basic_istream<_CharT, _Traits>& std::basic_istream<_CharT, _Traits>::read(_CharT*, std::streamsize) [with _CharT = char, _Traits = std::char_traits<char>]'
tld.hh:45: error: invalid conversion from 'void*' to 'char*'
tld.hh:45: error: initializing argument 1 of 'std::basic_istream<_CharT, _Traits>& std::basic_istream<_CharT, _Traits>::read(_CharT*, std::streamsize) [with _CharT = char, _Traits = std::char_traits<char>]'
第 39 行是第一个 fh.read() 调用。不知道我在这里做错了什么(除了我对这些事情的基本知识缺乏)。我也确信可能有一种方法可以在单个语句而不是循环中读取整个 origin 或 nextAvail 数组。