打开超过5 mb的文件并将其存储在阵列中

Opening files over 5 mb and storing them in an array

本文关键字:存储 阵列 文件 mb      更新时间:2023-10-16

我想把每个字节放在一个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();