【发布时间】:2011-03-11 08:33:59
【问题描述】:
我们有很多构建在 32 位机器上的缓存,现在我们必须在 64 位环境中读取这些缓存。 当我们想要打开读取缓存文件时,我们会遇到分段错误。
复制缓存需要数周时间,所以我想知道如何在 64 位机器上处理我们的 32 位缓存文件。
这是我们用来读写缓存的代码:
bool IntArray::fload(const char* fname, long offset, long _size){
long size = _size * sizeof(long);
long fd = open(fname, O_RDONLY);
if ( fd >0 ){
struct stat file_status;
if ( stat(fname, &file_status) == 0 ){
if ( offset < 0 || offset > file_status.st_size ){
std::__throw_out_of_range("offset out of range");
return false;
}
if ( size + offset > file_status.st_size ){
std::__throw_out_of_range("read size out of range");
return false;
}
void *map = mmap(NULL, file_status.st_size, PROT_READ, MAP_SHARED, fd, offset);
if (map == MAP_FAILED) {
close(fd);
std::__throw_runtime_error("Error mmapping the file");
return false;
}
this->resize(_size);
memcpy(this->values, map, size);
if (munmap(map, file_status.st_size) == -1) {
close(fd);
std::__throw_runtime_error("Error un-mmapping the file");
return false;
/* Decide here whether to close(fd) and exit() or not. Depends... */
}
close(fd);
return true;
}
}
return false;
}
bool IntArray::fsave(const char* fname){
long fd = open(fname, O_WRONLY | O_CREAT, 0644); //O_TRUNC
if ( fd >0 ){
long size = this->_size * sizeof(long);
long r = write(fd,this->values,size);
close(fd);
if ( r != size ){
std::__throw_runtime_error("Error writing the file");
}
return true;
}
return false;
}
【问题讨论】:
-
这些缓存包含什么?
-
如果您提供了正在读取的实际数据类型和您正在使用的平台,那将会很有趣。在一些 64 平台中,
long是 32 位,而在其他平台中是 64 位,这可以解释这个问题。附带说明一下,您不应该直接调用以__开头的方法,因为这些方法是为实现保留的,可以随时更改。如果你想抛出std::runtime_error,就这样做:throw std::runtime_error("my_error")