开发者

File Descriptors and System Calls

I am doing merging k-sorted streams using read write system calls.

After having read the first integers out of the files and sorting them, the file having the smallest element should be accessed again. I am not sure how 开发者_Go百科to do this. I thought I can use a structure like:

struct filePointer {
int ptr;
int num;
}fptr[5];

Can someone tell me how to do this.

Thanks


Although reading integers one-by-one is not an efficient way of doing this, I will try to write the solution that you are looking for. however this is not a real implementation, just the idea.

Your structure should be like this:

struct filePointer {
FILE * fp;
int num;
} fptr[k]; /* I assume k is constant, known at compile time */

You need to have an priority queue ( http://en.wikipedia.org/wiki/Priority_queue ) and prioities are determined accourding to num.

First read the first numbers from all files and insert them to priority queue (pq).

Then while pq is not empty, pop the first element which holds the smallest integer compared to other elements in the pq.

Write the integer that first element holds to file.

Using the file pointer (fp) try to read new integer from the input file.

If EOF (end of file), then do nothing

else insert the new element to pq by setting num to the read one.

When the loop is finished, close all files and you will have a new file that contains all the elements from the input files and it will be sorted.

I hope this helps.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜