file io

Hello, Im learning c++ and I'm not getting file io.

Im practicing making a little program, I have a customer array of structs with various member type like char, double, float, int and the array is called inputdetails, when the customer details are entered im meant to put the details in a text file to be read later on, all very straight forward.

I know how to write a struct but completely clueless on how to read it back, which isnt much use really :) Ive searched the net and I have a c++ cheat sheet for my ipad which shows you how to do text but no structs and arrays also there seems to be a few ways to do things and im confused.

At the bottom of this code i need to read all the data in the text file and cout it too the screen even all the customers that were added in earlier sessions because im adding to it all the time.


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

void writefile(int i, int p, customer inputdetails[])
{
	//open customernumber file and get number
	ifstream custnumber;
	custnumber.open("D:/hfiles/counter.txt");
	if(!custnumber){
		cout << "Error opening file";
		system("pause");
	}
	//copy value contained in textfile to customernumber member of struct
	custnumber >> p;
		inputdetails[i].customernumber = p;
	custnumber.close();
	
	//write details to database.txt as binary
	ofstream database;
	database.open("D:/hfiles/database.txt",ios::binary|ios::ate|ios::app);
	if (!database){
		cout << "Error opening File" << endl;
		system("pause");
	}
	database.write((char *)&inputdetails[i], sizeof(customer));
	database.close();
	cout << "Written to database" << endl;

	//update customernumber
	p++;
	ofstream counternumber;
	counternumber.open("D:/hfiles/counter.txt",ios::trunc);
	counternumber << p;
	counternumber.close();

	cout << "Customer number == " << p <<endl;
	system("pause");



Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
struct Foo {
    int n;
    std::string s;
};

Foo f;
std::ofstream ofs("file.txt");
ofs << f.n << ' ' << f.s;
ofs.close();

Foo g;
std::ifstream ifs("file.txt");
ifs >> g.n >> g.s;
ifs.close()

Notice that the extraction operator skips whitespace.
Topic archived. No new replies allowed.