如何使用C ++在> 4GB文件中写入数据? [英] How to write data in >4GB file with C++?
本文介绍了如何使用C ++在> 4GB文件中写入数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试写一个大文件,但是遇到了问题.
I'm trying to write a large file, but ran into a problem.
我花了很长时间寻找写入位置,但是写入的文件不能超过4,2Gb.我忘记了什么?
I use long long for seeking a place to write, but can't write file more than 4,2Gb. What I forgot?
更多详细信息: 我打开4Gb文件:
More details: I open 4Gb-file:
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文件,我想将其添加到数据库中.并编写(这是短代码):
After that, I read 400Mb-file, which I want to add to the db. And write (here is the short code):
// 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();
之后,我保存数据库信息:
After that, I save db info:
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();
For accessing the large files , fseek cannot be used , instead have to go for fseeko64();
这篇关于如何使用C ++在> 4GB文件中写入数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文