C语言对大数据文件进行快速排序

新手上路,请多包涵

打算用C语言对大的数据文件(500M左右)进行逆序处理,即:按照文件行从尾到头对数据文件进行存储。

目前的思路:用双向链表进行处理,文件函数如下所示。

请教的是:1)下面的函数是否有不合理的地方(比如内存溢出等)? 2) 还有没有更加高效快速的方式?

int main(char FilePath[], char PositiveName[], char NegativeName[])
{
    struct st {
        char c[4096];
        struct st *up;
        struct st *down;
    }*head, *tp, *next;

    head = (struct st*)malloc(sizeof(struct st));

    char FilePositive[300] = { " " };
    strcpy(FilePositive, FilePath);
    strcat(FilePositive, PositiveName);
    FILE *fPPOS = fopen(FilePositive, "rb");

    char FileNegative[300] = { " " };
    strcpy(FileNegative, FilePath);
    strcat(FileNegative, NegativeName);
    FILE *fPNEG = fopen(FileNegative, "wb");
    tp = head;
    tp->up = head;
    while (!feof(fPPOS))
    {
        next = (struct st*)malloc(sizeof(struct st));
        fgets(next->c, 768, fPPOS);
        tp->down = next;
        next->up = tp;
        tp = next;
    }
    
    tp->down = NULL;
    while (tp->up != head)
    {
        fputs(tp->c, fPNEG);
        tp = tp->up;
    }
    free(head);
    fputs(tp->c, fPNEG);
    
    fclose(fPPOS);
    fclose(fPNEG);
    return 1;
}
阅读 2k
1 个回答

考虑到你每次读取的块大小都是 768 字节,其实不需要用到链表,边读边写即可。

大概是这样的

#define BLOCK_SIZE 768

FILE *posFile = fopen(..., 'rb');
FILE *negFile = fopen(..., 'wb');

fseek(posFile, 0, SEEK_END);  // 移动到输入文件尾部
long size = ftell(posFile);
long position = size - BLOCK_SIZE;
while (position >= 0) {
  fseek(posFile, position, SEEK_SET);
  fread(buffer, 1, BLOCK_SIZE, posFile);
  fwrite(buffer, 1, BLOCK_SIZE, negFile);
  position -= BLOCK_SIZE;
}
...
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进