首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >fwrite的问题

fwrite的问题
EN

Stack Overflow用户
提问于 2015-05-20 02:09:32
回答 1查看 419关注 0票数 0

我正在对一个赋值进行外部合并排序,我得到了两个结构:

代码语言:javascript
复制
    // 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;

另外,我还得到了这样的信息:

代码语言:javascript
复制
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,我像这样分配内存:

代码语言:javascript
复制
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));

然后,在我从二进制文件中读取记录(运行流畅)后,我使用以下命令将它们写入多个文件(当然,在排序和一些其他步骤之后):

代码语言:javascript
复制
outputfile = fopen(name.c_str(), "wb");
fwrite(records, recordsIndex, sizeof(record_t), outputfile);

读起来像这样:

代码语言:javascript
复制
fread(&buffer[b].entries[rec],sizeof(record_t),1,currentFiles[b])

而且它起作用了!然后,我想将其中一些文件组合在一起,使用转到minheap的priority_queue生成更大的排序文件(它经过测试,可以正常工作),但是当我尝试使用以下命令写入文件时:

代码语言:javascript
复制
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())清除缓冲区。

EN

回答 1

Stack Overflow用户

发布于 2015-05-23 17:52:36

最后,主要问题是我试图打开文件的方式:

代码语言:javascript
复制
outputfile = fopen(outputName.c_str(), "ab"); //Opens file for appending

相反,我应该再次使用:

代码语言:javascript
复制
outputfile = fopen(outputName.c_str(), "wb"); //Opens file for writing to end of file

因为文件在此期间从未关闭,所以它试图打开一个已经打开的文件进行追加,但效果不是很好。但是你不可能知道,因为你没有完整的代码。谢谢您的帮助!:)

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/30333036

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档