fstream测试程序由于某种原因崩溃了

时间:2016-12-24 19:07:06

标签: c++ crash console-application fstream

我一直在使用C ++中的fstream类来查看我是否能够将一些数据写入文本文件(.txt)。据我所知,如果程序试图写入一个不存在的文件,那么它会自动创建该文件,我错了吗?这个程序非常简单,并没有给我任何编译器错误,这意味着它构建良好。但是由于某种原因,当我运行它时会崩溃。

这是我的代码:

#include <iostream>
#include <string>
#include <stdlib.h>
#include <fstream>

std::fstream* myFile;

int main()
{
int age = 15;
std::string myName = "Javier Martinez";
std::string friendsName = "David Lyn";
//Backslash is a special character, use double backslash or forward slash instead.
myFile->open("C:/Users/NIKE/Desktop/data.txt");
if (myFile->fail())
{
    std::cerr << "File was unable to be opened.";
}
*myFile << age << "\n";
*myFile << myName << "\n";
*myFile << friendsName << "\n";
myFile->close();
std::cout << "File was successfully written to with the data";
return 0;
}

感谢任何帮助。先感谢您。 注意:我使用GNU GCC编译器和Code :: Blocks IDE

3 个答案:

答案 0 :(得分:2)

myFile未初始化。检查它。(分配内存)或只使用fstream。

答案 1 :(得分:1)

你的问题源于这一行:

std::fstream* myFile;

您只声明了一个指向流对象的指针,该对象由于处于全局范围而初始化为nullptr。您尝试通过它访问不存在的对象(无效)的事实,您调用了所谓的Undefined Behavior

您不需要在堆上分配流对象,而是执行:

std::fstream myFile;

旁边注意:检查程序控制流程:

if (!myFile)
{
    std::cerr << "File was unable to be opened.";
}
else{
    myFile << age << "\n";
    myFile << myName << "\n";
    myFile << friendsName << "\n";
}

答案 2 :(得分:0)

两个问题

1 - myFile未初始化。

2 - 如果if-statement为真,则会打印错误消息但如果为真,则if-statement下的代码行不应执行。您需要将它们包含在else-statement

if (myFile->fail())
{
    std::cerr << "File was unable to be opened.";
}
else
{
   *myFile << age << "\n";
   *myFile << myName << "\n";
   *myFile << friendsName << "\n";
   myFile->close();
   std::cout << "File was successfully written to with the data";
}