【问题标题】:Segfault during file read文件读取期间的段错误
【发布时间】:2012-05-31 22:52:29
【问题描述】:

程序应该提示用户输入他们的用户名。收到用户名后,它会将其与“.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])

任何帮助将不胜感激。

【问题讨论】:

  • “username.history”的每一行是否少于50个字符?
  • 应该是,但一开始应该没关系,因为文件在第一次运行时不存在。
  • 为什么在 C++ 程序中使用strcat(C 程序员认为不安全)?使用std::string,生活会突然变得轻松许多。
  • 附注:当您阅读f_in &gt;&gt; tmp; 时,一旦读取文件的最后一个元素,f_in.eof() 仍然为 false。您应该在读取之后检查 eof 。像这样写它可以完美地工作:while (f_in &gt;&gt; tmp) { strcpy(cmd[fcount], tmp); ++fcount; }
  • Shahbaz 解决了所有问题。如果您提交答案,我会将其标记为正确。谢谢!

标签: c++ segmentation-fault


【解决方案1】:

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

【讨论】:

    【解决方案2】:
    而(f_in.good()) { f_in >> tmp; cmd[fcount] = tmp; fcount++; }

    【讨论】:

    • 查看我对这个问题的评论,这个循环尝试在数组到达 eof 后添加一个 unsuccessfully-read 值。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-05
    • 1970-01-01
    • 1970-01-01
    • 2023-03-12
    相关资源
    最近更新 更多