因此,我目前正在编写一个行编辑器,作为有关I / O的学习项目,编写文件等。它是用C ++编写的,我目前正在尝试写出用户选择的文件。我已经实现了CLI参数,但是目前我不知道如何以编程方式实现指定要写入的文件。
char *filename;
if (argc >= 2){
filename = argv[1];
} else{
cout << "file>";
cin >> filename;
cin.ignore();
}
当我使用命令行参数时,这种方法效果很好。但是,无论何时不执行,只要启动程序,它就会出现分段错误。我使用实际文件名的位置在save命令中:
void save(char filename[], int textlen, string file[]){
ofstream out(filename);
out << filestring(textlen, file);
out.close();
}
效果也很好。有什么办法可以帮助我吗?完整的源代码供审查,位于https://github.com/GBGamer/SLED。
问题在于,这char* filename
只是指向包含字符的某些内存的指针。它本身不拥有任何内存。当您使用命令行参数时,程序将把该字符串存储在某个地方,并获得指向它的指针。当您尝试使用进行读取时cin >> filename
,实际上没有任何地方可以存储读取的数据。
解决方案:替换char* filename
为std::string filename
(和#include <string>
)。
然后,要打开输出文件,您需要一个c样式的字符串(以空终止的char
数组)。std::string
具有此功能。你会写
std::ofstream out(filename.c_str());
^^^^^
或者,实际上,如果您可以使用具有c ++ 11功能的最新编译器,则甚至无需使用c_str()
。添加了新的std::ofstream
构造函数以接受std::string
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句