Write/read strings to/from file

Ok, so I need this program to write files on the first run, and that part works. But then I need it to be able to read from the file after it has written them. And that's where I encounter problems.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#include <iostream>
#include <io.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <cstdlib>
#include <string>
#include <ctime> 
#include <cctype>
#include <algorithm>
#include <fstream>
#using <mscorlib.dll>
using namespace System;
using namespace System::IO;
using namespace std;

string input;
string mainscene = "text removed";
string scene1 = "text removed";
void writeFiles(){
	ofstream fout;
	fout.open("C:\\Unravelling_Darkness\\BIN\\main.dat");
	fout<<mainscene;
	fout << flush;
	fout.close();
}
void gameStart(){
	/*I tried having display as a string and got an error saying "cannot convert string to char *"*/
        char *display;
	ifstream fin("C:\\Unravelling_Darkness\\BIN\\main.dat");
	fin.getline(display, 1000);
	system("Pause");
}
int main(){
	string strPath = "C:\\Unravelling_Darkness\\BIN\\";

   if ( access( strPath.c_str(), 0 ) == 0 )
   {   
	   cout<<"All necessary files are present. ";
	   system("Pause");
	   gameStart();
   }
   else
   {
		cout<<"No files are present. Would you like to create them? (Y/N): ";
		cin>>input;
		   if (input=="yes" | input == "y"){
				Directory::CreateDirectory("c:\\Unravelling_Darkness\\BIN\\");
				Directory::CreateDirectory("c:\\Unravelling_Darkness\\Saves\\");
				writeFiles();
				gameStart();
		   }
		   else return 0;
   }

}


Does anyone know how I can fix this?
Last edited on
You have not allocated any memory to your char* so this will likely cause a seg-fault:
1
2
3
4
5
6
7
void gameStart(){

        char *display; // no memory allocated..... should be char* display = new char[1000];
	ifstream fin("C:\\Unravelling_Darkness\\BIN\\main.dat");
	fin.getline(display, 1000);
	system("Pause");
}

Better to use std::string like this:
1
2
3
4
5
6
7
void gameStart(){
	
        std::string display;
	ifstream fin("C:\\Unravelling_Darkness\\BIN\\main.dat");
	std::getline(fin, display);
	system("Pause");
}

Last edited on
That worked, thank you very much.
Is there anyway I can have it read the entire document? it only reads the one line.

Edit: Nevermind saw another topic
Last edited on
Topic archived. No new replies allowed.