打开超过5 mb的文件并将其存储在阵列中
Opening files over 5 mb and storing them in an array
我想把每个字节放在一个char数组中,并重写文本文件,删除前100000个字符。
int fs=0;
ifstream nm,nm1;
nm1.open("C:\Dev-Cpp\DCS\Decom\a.txt");
if(nm1.is_open())
{
nm1.seekg(0, ios::end );
fs = nm1.tellg();
}
nm1.close();
char ss[500000];
nm.open("C:\Dev-Cpp\DCS\Decom\a.txt");
nm.read(ss,fs-1);
nm.close();
ofstream om;
om.open("C:\Dev-Cpp\DCS\Decom\a.txt");
for(int i=100000;i<fs-1;i++){
om >> ss[i];
}
om.close();
问题是我无法将字符数组设置为500万大小。我试着使用矢量也
vector <char> ss (5000000);
int w=0;
ifstream in2("C:\Dev-Cpp\DCS\Decom\a.txt", ios::binary);
unsigned char c2;
while( in2.read((char *)&c2, 1) )
{
in2 >> ss[w];
w++;
}
在这里,w的大小几乎是fs的一半,并且缺少了很多字符。
怎么做?
在大多数实现中,char ss[5000000]
尝试在堆栈上进行分配,与整体内存大小相比,堆栈的大小是有限的。您通常可以在堆上分配比在堆栈上更大的数组,如下所示:
char *ss = new char [5000000];
// Use ss as usual
delete[] ss; // Do not forget to delete
请注意,如果文件大小fs
大于5000000,您将写入缓冲区的末尾。您应该限制您读取的数据量:
nm.read(ss,min(5000000,fs-1));
此部件不是正确的
while( in2.read((char *)&c2, 1) )
{
in2 >> ss[w];
w++;
}
因为您首先尝试将一个字符读取到c2
中,如果成功,则将另一个字符读取到ss[w]
中。
如果你在这里失去了大约一半的角色,我一点也不惊讶!
解决问题的最佳方法是使用标准库的设施。这样,您也不必关心缓冲区溢出。
以下代码未经测试。
std::fstream file("C:\Dev-Cpp\DCS\Decom\a.txt", std::ios_base::in);
if (!file)
{
std::cerr << "could not open file C:\Dev-Cpp\DCS\Decom\a.txt for readingn";
exit(1);
}
std::vector<char> ss; // do *not* give a size here
ss.reserve(5000000); // *expected* size
// if the file is too large, the capacity will automatically be extended
std::copy(std::istreambuf_iterator<char>(file), std::istreambuf_iterator<char>(),
std::back_inserter(ss));
file.close();
file.open("C:\Dev-Cpp\DCS\Decom\a.txt", std::ios_base::out | std::ios_base::trunc);
if (!file)
{
std::cerr << "could not open C:\Dev-Cpp\DCS\Decom\a.txt for writingn";
exit(1);
}
if (ss.size() > 100000) // only if the file actually contained more than 100000 characters
std::copy(ss.begin()+100000, ss.end(), std::ostreambuf_iterator<char>(file));
file.close();
相关文章:
- 将一个阵列中的数据存储到另外两个阵列中不起作用
- 阵列的临时存储如何用于C++中的删除恢复?
- 如何在阵列中存储多个队列?
- 内存中的阵列存储
- 在字符阵列C 中存储整数值
- 如何将整个单词存储在单个阵列插槽中
- 将25个甚至整数存储到一个名为intlist的整数阵列中,然后在屏幕上显示数组,并在屏幕上显示名为fivintegers
- 我如何将整数转换为存储在字符阵列中的十六进制字节
- 需要将单词的文本文件存储到C 中的字符阵列中
- 将指针或一系列指针存储在动态阵列中
- 如何将整数存储在字符阵列中
- 将多个功能存储到阵列C 以进行循环
- 存储文件中的字符串,但是数组仍然为空?阵列大小的循环
- C 私有阵列访问和存储
- 将文件从文件存储到阵列C
- 存储矢量中的动态阵列
- 2D阵列和1D阵列存储比较
- 将整数从for循环存储在全球阵列中
- 将阵列存储到动态内存中
- 将数据存储到多维阵列中