文件读取期间的隔离错误

Segfault during file read

本文关键字:隔离 错误 读取 文件      更新时间:2023-10-16

程序应该提示用户输入用户名。 收到用户名后,它会将其与".history"连接以创建用户名.history。 然后它打开该文件(用户名.history)并从中读取输入。 不过,我在这里遇到了一个段错误。 每当它打开文件(由于文件不存在而为空)时,它都会读取多行,然后抛出段错误。 我认为问题可能源于我尝试打开文件的方式,但我不确定。 以下是导致问题的部分:

// File input and output
ifstream f_in;
ofstream f_out;
// Prompt user for their username.
char username[80];
cout << "Please input your username: " << endl;
cin >> username;
cout << endl;
cout << "Loading history file if it exists." << endl;
// Create file naem and initialize the file line counter to 0.
strcat(username, ".history");
int fcount = 0;
// Open file and read in lines if there are any.
// Place read lines into the command string for use later.
char tmp[50];
f_in.open(username);
while(!f_in.eof()){
    f_in >> tmp;
    cmd[fcount] = tmp;
    fcount++;
}
f_in.close();

其他相关信息:cmd 被声明为全局变量(char cmd[200][50])

任何帮助都将得到极大的赞赏。

不确定这是否是唯一的问题,但cmd[fcount] = tmp是错误的。您应该使用 strcpy() .

而(f_in.good()){    f_in>> TMP;    cmd[fcount] = tmp;    fcount++;}