0
从C或C++,我想读取尽可能快的二进制格式的双份文件。Cpp读取双倍快速小型二进制文件
文件很小,通常在100KB左右(200 KB上)。我希望能够:
- 阅读双打文件。
- 转换/将它们存储在双精度矢量中
- 遍历矢量。
然后在2毫秒内完成。如果可能,在这个系统上。目前它大约在4-6毫秒。
线程帮助,但没有解决的问题:
Link 2 - >这甚至没有编译。
Link 3 - >这对双打没有效果。
Link 4 - >这样做。
这里是我的文件分析器:
阅读“C” 样式:
void OfflineAnalyser::readNParseData(const char* filePath, vector<double> *&data){
// Temporary Variables
FILE* pFile;
long fileSize;
double *fileBuffer;
size_t sizeOfBuffer;
size_t result;
// Open File
pFile = fopen(filePath, "rb");
if (pFile == NULL){
cout << "File: " << filePath << " does not exist" << endl;
}
// Check whether the parameter is already full
if (!data){
// Reset the output
data->clear();
data = 0;
}
// Obtain file size:
fseek(pFile, 0, SEEK_END);
fileSize = ftell(pFile);
rewind(pFile);
// allocate memory to contain the whole file:
fileBuffer = (double*)malloc(fileSize);
if (fileBuffer == NULL) { fputs("Memory error", stderr); exit(2); }
// copy the file into the buffer:
result = fread(fileBuffer, 1, fileSize, pFile);
if (result != fileSize) {
fputs("Reading error", stderr);
system("pause");
exit(3);
}
// the whole file is now loaded in the memory buffer.
sizeOfBuffer = result/sizeof(double);
// Now convert the double array into vector
data = new vector<double>(fileBuffer, fileBuffer + sizeOfBuffer);
free(fileBuffer);
// terminate
fclose(pFile);
}
方法2:C++风格
void OfflineAnalyser::readNParseData2(const char* filePath, vector<double> *&data){
ifstream ifs(filePath, ios::in | ios::binary);
// If this is a valid file
if (ifs) {
// Temporary Variables
std::streampos fileSize;
double *fileBuffer;
size_t sizeOfBuffer;
// Check whether the parameter is already full
if (!data){
// Reset the output
data->clear();
data = 0;
}
// Get the size of the file
ifs.seekg(0, std::ios::end);
fileSize = ifs.tellg();
ifs.seekg(0, std::ios::beg);
sizeOfBuffer = fileSize/sizeof(double);
fileBuffer = new double[sizeOfBuffer];
ifs.read(reinterpret_cast<char*>(fileBuffer), fileSize);
// Now convert the double array into vector
data = new vector<double>(fileBuffer, fileBuffer + sizeOfBuffer);
free(fileBuffer);
}
}
任何建议到这个代码非常感谢。随意输入你自己的代码。 如果我能看到双打或istream_iterator解决方案的std :: copy,我会很高兴。
在此先感谢。
没有错误。我上面给出的代码工作得非常好(如果数据为空(0),!数据将是1,它将进入if)。事实上,我已经试过你的代码与一个指针不得不修复以下两行,让人感受:if(!data-> empty()){]给出exp和data-> resize(fileSize/8);也给出例外。修正了它们,但fread也会产生异常。所以我尝试了你的代码版本(正是你上面给出的代码)。读取的double值不正确。我正在从Hex编辑器和我自己的代码中检查两者。返回的值不正确。可能你可以修改你的代码? – JohnJohn
哦,我的道歉,我调用函数之前,我调用函数“矢量 *数据= 0”,然后我调用函数,我现在正在做一个if(data!= 0)检查。感谢您指出了这一点。 –
JohnJohn