文件读取期间的Segfault

时间:2012-05-31 22:52:30

标签: c++ segmentation-fault

程序应该提示用户输入用户名。收到用户名后,它会将其与'.history'连接起来以创建username.history。然后它打开该文件(username.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])

任何帮助都会受到很大的影响。

2 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:0)

while(f_in.good())
{
    f_in >> tmp;
    cmd[fcount] = tmp;
    fcount++;
}
相关问题