1

I have been playing around with the fstream class in C++ to see if I am able to write some data to a text file(.txt). According to what I know, If the program tries to write to a file that does not exist then it would automatically create that file, am I wrong? This program is very simple and does not give me any compiler errors which means it builds fine. However for some reason it crashes when I run it.

Here is my code:

#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;
}

Any help is appreciated. Thank you in advance. NOTE: I am using the GNU GCC compiler with Code::Blocks IDE

  • 1
    *This program is very simple* -- But you made it more difficult by introducing pointers for no reason. -- *and does not give me any compiler errors which means it builds fine* -- A program building fine only means there are no syntax errors. It doesn't determine if the program will run correctly. – PaulMcKenzie Dec 24 '16 at 19:20
  • @PaulMcKenzie You're right. That's why I removed the pointer since I am trying to fix my program right now. –  Dec 24 '16 at 19:32

2 Answers2

2

myFile is uninitialized. Check it.( Allocate memory) or simply use fstream.

user2736738
  • 30,591
  • 5
  • 42
  • 56
1

Your problem stems from the line:

std::fstream* myFile;

You only declared a pointer to a stream object, which is initialized to nullptr by reason of it being in the global scope. The fact that you tried accessing a non-existent object (invalid) through it, you invoked what is known as Undefined Behavior.

You do not need to allocate stream objects on the heap, rather, do:

std::fstream myFile;

On a side Note: Check your program control flow:

if (!myFile)
{
    std::cerr << "File was unable to be opened.";
}
else{
    myFile << age << "\n";
    myFile << myName << "\n";
    myFile << friendsName << "\n";
}
Community
  • 1
  • 1
WhiZTiM
  • 21,207
  • 4
  • 43
  • 68