c++ 文件如何删除数据和插入数据

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

阅读 4.8k
2 个回答

没人回答那我自己来吧

#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;
}

设计好文件格式,学人家数据库的存储方法,例如B+树。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题