fstream tags

I've just been learning about basic file operation in my Intro to C++ textbook. The book states that "dataFile.open("file.txt", ios::in | ios::out)" should allow me to use the file in both input and output, as well as create the file if it doesn't already exist. Curious, I gave it a try in Microsoft Visual.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
#include <fstream>
using namespace std;

int main()
{
	char temp[50];		//To hold the input from file.

	fstream dataFile;
	dataFile.open("file.txt", ios::in |ios::out);
	
	cout << "Writing in file...\n";
	dataFile << "Hello there!\n";

	cout << "\nReading from file...\n";
	dataFile >> temp;
	cout << temp << endl;

	dataFile.close();

	system("PAUSE");
	return 0;

}



However, when debugging the program, the file is not created and nothing is written onto it. What am I doing wrong?
I can't check it now, but I think you should change:

dataFile.open("file.txt", ios::in |ios::out);

for:

dataFile.open("file.txt", ios::trunc|ios::in |ios::out);

Also:

dataFile >> temp;

for:

dataFile.getline(temp, 50);

If you want to read this file, you should also put pointer in beggining, so add this:

dataFile.seekp(0);

before:

cout << "\nReading from file...\n";

I think this should help.
Last edited on
Topic archived. No new replies allowed.