鍍金池/ 問答/Java  C  C++/ c++ 文件如何刪除數(shù)據(jù)和插入數(shù)據(jù)

c++ 文件如何刪除數(shù)據(jù)和插入數(shù)據(jù)

文件將近1G,有什么高效的方法

回答
編輯回答
喜歡你

沒人回答那我自己來吧

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
typedef unsigned char byte;

bool removeBytes(FILE *stream, int length) {
    if (length <= 0)
        return true;
    long pos1, pos2, oldLength, newLength, off;
    pos1 = pos2 = ftell(stream);
    fseek(stream, 0, 2);
    oldLength = ftell(stream);
    fseek(stream, pos1, 0);
    newLength = oldLength - length;
    off = newLength - pos1;
    while (off > 0) {
        int cSize = off>0x1000?0x1000:off;
        char *cache = new char[cSize];
        off -= cSize;
        if (fseek(stream, pos2 + length, 0)||
            fread(cache, 1, cSize, stream) != cSize||
            fseek(stream, pos2, 0)||
            fwrite(cache, 1, cSize, stream) != cSize)
            return false;
        pos2 += cSize;
        free(cache);
    }
    return !ftruncate(fileno(stream), newLength<pos1?pos1:newLength);
}

bool insertBytes(FILE *stream, byte *bytes, long length = 4) {
    if (length < 0)
        return true;
    long pos, oldLength, newLength, off;
    pos = ftell(stream);
    fseek(stream, 0, 2);
    oldLength = ftell(stream);
    fseek(stream, pos, 0);
    newLength = oldLength + length;
    off = oldLength - pos;
    if (ftruncate(fileno(stream), newLength))
        return false;
    while (off > 0) {
        int cSize = off>0x1000?0x1000:off;
        char *cache = new char[cSize];
        off -= cSize;
        if (fseek(stream, pos + off, 0)||
            fread(cache, 1, cSize, stream) != cSize||
            fseek(stream, pos + length + off, 0)||
            fwrite(cache, 1, cSize, stream) != cSize)
            return false;
        free(cache);
    }
    fseek(stream, pos, 0);
    if (fwrite(bytes, 1, length, stream) == length)
        return true;
    return false;
}
2018年6月27日 09:13
編輯回答
離夢(mèng)

設(shè)計(jì)好文件格式,學(xué)人家數(shù)據(jù)庫的存儲(chǔ)方法,例如B+樹。

2018年8月28日 06:38