加载大型文本文件(50,000多行,〜8MB)会导致我的程序停止

Loading in large text file (50,000+ lines, ~8MB) causes my program to stop?

本文关键字:我的 程序 8MB 文件 文本 大型 多行 加载      更新时间:2023-10-16

回答:

更改

while (tracefile->good()){
    getline(*tracefile,line);
....

to

while(getline(*tracefile, line)){
....

做到了。谢谢,@pmr。

原始:

我为我的计算机体系结构类制作了一个缓存模拟器,该类应该在包含我缓存的内存指令的跟踪文件中读取。

我在制作程序时只使用了一个只有1000行的测试跟踪文件,但是实际的跟踪文件为50k 行。通过测试跟踪,程序运行完美。使用实际的跟踪,该程序一直持续到尝试在一条线上使用.substr(),这会导致out_of_range异常并过早地停止我的程序。我调查了,发现getline()在痕迹太大时会提供空字符串。请记住,这不会发生在轨迹< = 〜5000行。

有人知道为什么会发生这种情况吗?我正在使用一个ifstream,如果很重要。

编辑:对不起,这是代码。它不会超越" ...."

主:

cout << "Program started.n";
string str[6];
int i = 0;
/* check for the correct number of arguments */
if(argc != 3){
    cout<<"usage: "<< argv[0] <<" <configfile> <tracefile>n";
    exit(0);
}
string confname = argv[1];
string tracename = argv[2];
/* open the files and check if it worked */
ifstream confile;
ifstream tracefile;
confile.open (argv[1], ios::in);
if (!confile.is_open()){
    cout<<"Could not open config file.n";
    exit(0);
}
if (confile.is_open()) cout << "Config file loaded.n";
tracefile.open (argv[2], ios::in);
if (!tracefile.is_open()){
    cout<<"Could not open trace file.n";
    exit(0);
}
if (tracefile.is_open()) cout << "Trace file loaded.n";
/* read in the data from the config file */
if (confile.is_open()){
    i = 0;
    while(confile.good() && i != 6){
        getline(confile, str[i]);
        i++;
    }
}
/* create the cache simulator */
cache csim(atoi(str[0].c_str()), atoi(str[1].c_str()), 
                atoi(str[2].c_str()), atoi(str[3].c_str()), 
                atoi(str[4].c_str()), atoi(str[5].c_str()));
cout << "Simulator started.n";
/* send the simulator the trace */
csim.trace(&tracefile);

csim.trace:

cout << "Going through trace...";
int i;
string line;
string tag, index, offset;
this->IC = 0;
/* loop until there is no more lines */
while (tracefile->good()){
    /* get the next line and increment the instruction counter */
    getline(*tracefile,line);
    this->IC++;
    /* convert hex address to a binary address */
    string address = "";
    for (i = 0; i < line.substr(4,8).length (); i++)
    {
....

看起来您的一个字符串可能还不够长。

while (getline(*tracefile,line);){
    /* get the next line and increment the instruction counter */
    this->IC++;
    /* convert hex address to a binary address */

    //be sure to check length of string
    if (line.size() < 12)
    {
        cerr << "line is too small" << endl;
        continue;
    }
    string address = "";
    string tmp_str = line.substr(4,8);
    for (i = 0; i < tmp_str.size(); i++) //tmp_str.size() will always be 8
    {
    }
}
相关文章: