以下是数据的编写方式:
FILE* f = fopen(FILENAME, "ab");
if(ferror(f) != 0) {
printf("fopen failed %d\n", ferror(f));
}
size_t written = 0;
written = fwrite(&key, sizeof(key), 1, f);
if(written != 1) {
printf("fwrite wrote %d elements, should have been %d\n", written, 1);
}
written = fwrite(&value, sizeof(value), 1, f);
if(written != 1) {
printf("fwrite wrote %d elements, should have been %d\n", written, 1);
}
if(ferror(f) != 0) {
printf("fwrite failed %d\n", ferror(f));
}
fclose(f);
以下是数据的读取方式:
FILE* f = fopen(FILENAME, "rb");
if(ferror(f) != 0) {
printf("fopen failed %d\n", ferror(f));
}
uint64_t key = 0;
uint64_t value = 0;
size_t read = 0;
while(!feof(f)) {
read = fread(&key, sizeof(key), 1, f);
if(read != 1) {
printf("fread read %d elements, should have been %d\n", read, 1);
}
read = fread(&value, sizeof(value), 1, f);
if(read != 1) {
printf("fread read %d elements, should have been %d\n", read, 1);
}
if(ferror(f) != 0) {
printf("fread failed %d\n", ferror(f));
}
if(key == 0 || value == 0) {
printf("fread output was key = %llu, value = %llu\n", k, value);
}
if(key == arg) {
fclose(f);
return value;
}
}
printf("EOF reached, returning 0\n");
fclose(f);
return 0;
现在就是这个难题:没有触发printf调试/错误语句。就我而言,我正确地打开和关闭文件,我正在编写和读取正确数量的(正确大小)元素,并且没有任何杂项错误输出。
但是,读取的值有时与写入的值不同。这种情况很少发生,也许每30到50次运行一次,但在这种情况下的影响是灾难性的,因为在我的情况下它会导致我的程序崩溃。这是我的调试语句中的一些输出直接在函数之外(应该没有代码可以以任何方式改变值):
Saving key-value pair to store failed, wrote value 1930602754145344693, read value 7983440653331291317
File contents:
key 32385216, value 10451404324075904545
key 32385152, value 8261841165554445677
key 32384944, value 7948309595355207668
key 32384320, value 79834406533311291317
文件中没有重复的键(或值)。
你能给我任何指导如何调试这样的问题吗?对我而言,问题似乎不在我的计划之内,但我不确定是否会出现这种情况。我的操作系统是Windows 7 x64,而且我正在写入我的系统SSD磁盘,这应该不会有任何错误(我认为我写的文件实际上是由Windows一直缓存在RAM中的因为经常访问)。