我正在对一个赋值进行外部合并排序,我得到了两个结构:
// This is the definition of a record of the input file. Contains three fields, recid, num and str
typedef struct {
unsigned int recid;
unsigned int num;
char str[STR_LENGTH];
bool valid; // if set, then this record is valid
int blockID; //The block the record belongs too -> Used only for minheap
} record_t;
// This is the definition of a block, which contains a number of fixed-sized records
typedef struct {
unsigned int blockid;
unsigned int nreserved; // how many reserved entries
record_t entries[MAX_RECORDS_PER_BLOCK]; // array of records
bool valid; // if set, then this block is valid
unsigned char misc;
unsigned int next_blockid;
unsigned int dummy;
} block_t;另外,我还得到了这样的信息:
void MergeSort (char *infile, unsigned char field, block_t *buffer,
unsigned int nmem_blocks, char *outfile,
unsigned int *nsorted_segs, unsigned int *npasses,
unsigned int *nios)现在,在阶段0,我像这样分配内存:
buffer = (block_t *) malloc (sizeof(block_t)*nmem_blocks);
//Allocate disc space for records in buffer
record_t *records = (record_t*)malloc(nmem_blocks*MAX_RECORDS_PER_BLOCK*sizeof(record_t));然后,在我从二进制文件中读取记录(运行流畅)后,我使用以下命令将它们写入多个文件(当然,在排序和一些其他步骤之后):
outputfile = fopen(name.c_str(), "wb");
fwrite(records, recordsIndex, sizeof(record_t), outputfile);读起来像这样:
fread(&buffer[b].entries[rec],sizeof(record_t),1,currentFiles[b])而且它起作用了!然后,我想将其中一些文件组合在一起,使用转到minheap的priority_queue生成更大的排序文件(它经过测试,可以正常工作),但是当我尝试使用以下命令写入文件时:
outputfile = fopen(outputName.c_str(), "ab"); //Opens file for appending
fwrite(&buffer[nmem_blocks-1].entries, buffer[nmem_blocks-1].
nreserved, sizeof(record_t), outputfile);它在文件中写入无用信息,就好像它读取内存的随机部分一样。
我知道代码可能还不够,但所有的代码都相当大。在使用新名称再次打开输出文件之前,我要确保将其关闭。另外,在再次填充缓冲区之前,我使用memset() (而不是free())清除缓冲区。
发布于 2015-05-23 17:52:36
最后,主要问题是我试图打开文件的方式:
outputfile = fopen(outputName.c_str(), "ab"); //Opens file for appending相反,我应该再次使用:
outputfile = fopen(outputName.c_str(), "wb"); //Opens file for writing to end of file因为文件在此期间从未关闭,所以它试图打开一个已经打开的文件进行追加,但效果不是很好。但是你不可能知道,因为你没有完整的代码。谢谢您的帮助!:)
https://stackoverflow.com/questions/30333036
复制相似问题