Can't write a .txt file

What's wrong with this code?


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
void fWriteChar(int WriteChar)
{
	//Writes Char Color file
	fstream WriteCharacter;
	WriteCharacter.open("Char.txt");
	if (WriteCharacter)
	{
		cout << "Worked";
	}
	else
	{
		cout << "Didn't work\n";
	}
	WriteCharacter << WriteChar;
	WriteCharacter.close();
}
There should be more of it. This isn't your whole program is it?

Also, you want Line 6 to be:
 
if (WriteCharacter.is_open())

and you'll want to add return; after Line 12.
Last edited on
No this is just a function that writes file... Or is supposed to. the if statment was to help me figure out why It wasn't writing anything.

so What I want to do is this:
1
2
3
4
	fstream WriteCharacter;
	WriteCharacter.open("Char.txt");
	WriteCharacter << WriteChar;
	WriteCharacter.close();


is that not how to create, and write a .txt file?
Looks ok to me. What about the rest of your code?
You know what... I tried ofstream before I tried fstream. And not ofstream works!

Anyway thanks it works now... For some reason...

EDIT: @CompterGeek01, Appearently I just needed to add the 'O' back to 'ofstream'.
I have a love hate relationship with this language.
Last edited on
I think it isn't possible to write to fstream files for some reason (altought it is write and read)

When I want to write and read to a file I use something like this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
ifstream ifFile;
ofstream ofFile;
string line;

if( read )
{
     ifstream.open("file.txt");
     getline(ifstream, line);
     ifstream.close();
}
if( write )
{
     ofstream.open("file.txt", ios::app);
     ofstream << "whatever text to write to file" << whateverstring << endl;
     ofstream.close();
}


Ofcourse it would be more complex, but I think I am never able to write to fstream files :|

Also, I noticed this in your code:
1
2
3
4
5
6
7
8
if (WriteCharacter)
	{
		cout << "Worked";
	}
	else
	{
		cout << "Didn't work\n";
	}

If you want to check if the file is open or you are able to access it, I think this would be better:
1
2
3
4
5
6
if(WriteCharacter.good())
{
     cout << "Worked" << endl; // Also, calling endl will change line in cmd ;)
}
else
     cout << "Didn't work\n"; // Ye, you can also use \n. 


if you want to check if you got to the end of file you can use:
WriteCharacter.eof() // if it returns true it means you reached the end of the file.

I hope I helped.
Last edited on
Topic archived. No new replies allowed.