gpt4 book ai didi

c++ - 如何使用 C++ 将数据写入大于 4GB 的文件?

转载 作者:可可西里 更新时间:2023-11-01 18:37:14 29 4
gpt4 key购买 nike

我正在尝试写入一个大文件,但遇到了问题。

我使用 long long 来寻找写入的地方,但不能写入超过 4,2Gb 的文件。我忘了什么?

更多详情:我打开 4Gb 文件:

ifstream ifs(db_name.c_str(), ios_base::binary);
if (!ifs)
throw Bad_archive();
ifs.read(as_bytes(seg_size), sizeof(int));
ifs.read(as_bytes(last_idx), sizeof(int));
ifs.read(as_bytes(free_segs), sizeof(int));
if (free_segs > 0)
{
long long seek_g = 3 * sizeof(int) + (long long)last_idx * seg_size;
ifs.seekg(seek_g, ios_base::beg);
for (int i = 0; i < free_segs; i++)
{
int tmp = 0;
ifs.read(as_bytes(tmp), sizeof(int));
free_spaces.push_back(tmp);
}
}
ifs.close();

之后,我读取了 400Mb 文件,我想将其添加到数据库中。并写(这里是短代码):

// write object
ofstream ofs(db_name.c_str(), ios_base::binary | ios_base::in | ios_base::ate);
for (int i = 0; ; i++)
{
// set stream position
long long write_position = sizeof(int) * 3;

...

write_position += (long long) seg_size * last_idx;
ofs.seekp(write_position, ios::beg);

...

// write sizeof object
if (i == 0)
ofs.write(as_bytes(object_size), sizeof(object_size));
else
{
int null = 0;
ofs.write(as_bytes(null), sizeof(null));
}

// write data
for (int j = 0; j < (seg_size - sizeof(int) * 2); j++)
{
ofs.write(as_bytes(obj_content[j + i * (seg_size - sizeof(int) * 2)]),
sizeof(char));

}
if (write_new_seg)
last_idx++;

...

ofs.write(as_bytes(cont_seg), sizeof(cont_seg));
}
ofs.close();

之后,我保存数据库信息:

if (last_idx == 0)
{
ofstream ofs(db_name.c_str());
ofs.close();
}
ofstream ofs(db_name.c_str(), ios_base::binary | ios_base::in |
ios_base::out | ios_base::ate);
long long seek_p = 0;
ofs.seekp(seek_p, ios_base::beg);
ofs.write(as_bytes(seg_size), sizeof(seg_size));
ofs.write(as_bytes(last_idx), sizeof(last_idx));
ofs.write(as_bytes(free_segs), sizeof(free_segs));
ofs.close();

但是这段代码有效:

ofstream ofs2("huge2");
ofs2.close();
ofstream ofs("huge2", ios_base::in | ios_base::ate);
long long sp = 10000000000;
ofs.seekp(10000000000, ios_base::beg);

ofs.write(as_bytes(sp), sizeof(sp));

ofs.close();

最佳答案

    fseeko64 (Filename, 0, SEEK_END);
long size = ftello64 (Filename);
fclose (Filename);

访问大文件,不能用fseek,必须用fseeko64();

关于c++ - 如何使用 C++ 将数据写入大于 4GB 的文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7135598/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com