写入文件时转储的核心

Core dumped when writing to file?

本文关键字:核心 转储 文件      更新时间:2023-10-16

嗨,这是我为C++文件I/o实践编写的一段非常简单的代码。但是当我运行这个时,我得到了一个Segmentation Fault (core dumped)异常。下面是我的代码:

# include <iostream>
# include <string>
# include <cmath>
# include <fstream>
using namespace std;
int main()
{
double num, rad, i, angle, x, y;
char * filename;
ofstream file;
// prompt  ask for number
cout << "Enter the number of sample points: ";
cin >> num;
// prompt for circle radius.
cout << "Enter the circle radius: ";
cin >> rad;
// prompt for output file name.
cout << "Enter the output filename: ";
cin >> filename;
file.open (filename, fstream :: in | fstream :: trunc);
if(!file.is_open())
{
    cout << "Error opening file " << filename << endl;
    cout << "Exiting..." << endl;
    return 0;
}
for(i = 1; i <= num; i ++)
{
    //angle = 2 * M_PI * (i/num);
    //x = rad * cos(angle);
    //y = rad * sin(angle);
    //file << "t" << x << "t" << y << endl;
    file << "this is " << i << endl;
}
cout << "finished";
file.close();
return 0;
}

我不确定问题出在哪里,但在输入输出文件名后会显示错误消息"seg fault(core dumped)"。

感谢

cin >> filename将是未定义的行为,因为filename是未初始化的指针。

如果要存储字符,则需要为它们分配空间。所以你可以做:

char filename[150] = {0};
cin >> filename; // OK, you provide space for 149 characters. Will still break
                 // if more characters are provided by the user.

或:

#include <string>
std::string filename; // overloads operators >> and << with streams
                      // automatically performs memory management
// std::cin >> filename; /* Would stop at first space */
std::getline(std::cin, filename); // better: will stop at any carriage return

请为文件名分配一些内存,您只能使用ponter。更改

char  filename[50];