2012-01-14 28 views
0

我想将每个字节放入一个字符数组中,并重写该文本文件以除去前100,000个字符。打开超过5 MB的文件并将它们存储在一个数组中

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的一半,和很多人物的缺失。

怎么办?

回答

2

在大多数实现中,char ss[5000000]尝试在堆栈上进行分配,并且与整体内存大小相比,堆栈的大小是有限的。你可以经常在堆中分配较大的阵列比在栈上,像这样:

char *ss = new char [5000000]; 
// Use ss as usual 
delete[] ss; // Do not forget to delete 

注意,如果文件大小fs大于500万时,你会写了缓冲区的结尾。您应该限制数据的阅读量:

nm.read(ss,min(5000000,fs-1)); 
+0

谢谢,我用过char * ss = new char [5000000];如你所建议并删除[] ss;在程序结束时,它现在工作正常,但我没有堆和堆栈的经验,不知道在哪里放置size_t代码(在fstream里面?) – 2012-01-14 12:13:08

+0

@GambitKing最初你只需要粗略理解[堆vs 。stack](http://stackoverflow.com/questions/79923/what-and-where-are-the-stack-and-heap),你可以从五分钟的阅读中获得。我错了'size_t actualSize' - 请参阅我的编辑。 – dasblinkenlight 2012-01-14 12:24:03

+0

感谢您的信息 – 2012-01-14 12:30:31

1

这部分是不正确的

while(in2.read((char *)&c2, 1)) 
{ 
    in2 >> ss[w]; 
    w++; 
} 

bacause您第一次尝试读取一个字符为c2和,如果成功,读另一个字符分成ss[w]

如果你失去了大约一半的人物,我并不感到惊讶!

0

解决您的问题的最佳方法是使用标准库的设施。这样,你也不必关心缓冲区溢出问题。

以下代码未经测试。

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 reading\n"; 
    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 writing\n"; 
    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(); 
相关问题