fstream not writing to file

I have trouble again in writing to the file. Basically my program checks if the file is empty, if it is then you get the input and write to file. But, it does not write to file,and failbit is set.
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
56
57
58
59
60
#include<iostream>
#include<conio.h>
#include<fstream>
#include<cstdlib>
using namespace std;
class account
{
	int acno;
	double money;
	char name[10];
public:
	void input()
	{
		cout << "Enter Details: ";
		cin.getline(name, 10);
		cin >> acno;
		cin >> money;
	}
	void output()
	{
		cout <<endl<< name << endl << acno << endl << money;
	}
}obj;
bool empty(fstream& file)
{
	return file.peek() == std::ifstream::traits_type::eof();
        //Returns 1 if eof, otherwise 0.
}
int main()
{
	fstream file("acc.txt", ios::app|ios::out|ios::in);
	if (file.fail())
	{
		cout << "Failed" << endl << file.fail();
		getch();
		exit(0);
	}//This does not execute
	if (empty(file)==1)
	{
		obj.input();
		file.write((char *)&obj, sizeof(obj)); //This does not write
		if (file.fail())//This executes i.e the file fails to write
		{
			cout << "Failed" << endl << file.fail();
			_getch();
			exit(0);
		}
	}
	else//This is for displaying, the contents of the file.
	{
		file.seekg(0, ios::beg);
		while (file.peek() != EOF)
		{
			file.read((char *)&obj, sizeof(obj));
			obj.output();
		}
	}
	getch();
	return 0;
}


I have tested this with GCC and Microsoft Compilers both show the same output. I hope somebody can help me, I have been dealing with this for more than a day.
Last edited on
I have actually never seen anyone try to use std::fstream for file I/O, so I don't know if that is actually feasible or not. There are two child classes of std::fstream that are used for file I/O.

std::ifstream: File input. Used for reading data from a file into your program.
std::ofstream: File output. Used for outputting data from your program into a file.

The tutorial on this website covers very well how to use these classes. http://www.cplusplus.com/doc/tutorial/files/
I have actually never seen anyone try to use std::fstream for file I/O, so I don't know if that is actually feasible or not. There are two child classes of std::fstream that are used for file I/O.

Well I certainly do know, about them, but it's much easier to use one fstream object instead of creating two separately. According to the link which you specify here's what it says about fstream
fstream: Stream class to both read and write from/to files.
Last edited on
Okay, I got it to work, basically my empty function would set the failbit itself, since it reached the EOF, which would disallow the rest of the functions to work.
Thank you. :) I learned something new. Glad you got it figure out. Cheers!
Topic archived. No new replies allowed.