Append Records

Anyone can guide me?
I wish to append one more record to the sample.txt
Eg,

5 Thai Pon_Mak 0.0 0.0 0 Fail


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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <cstring>
using namespace std;

const int MAX = 20;
const int MAX1 = 30;

struct UKStudent
{
	char name [MAX1];
	int noTest;
	float mark [MAX];
	int final;
	char grade [MAX1];
};

struct OverseasStudent
{
	char country [MAX1];
	char name [MAX1];
	int noTest;
	float mark [MAX];
	int final;
	char grade [MAX1];
};

union EveryStudent
{
	UKStudent       uks;
	OverseasStudent	oss;
};

struct Student
{
	char type;   
	EveryStudent st;
};


void appendR (fstream&, char []);

int main()
{

	fstream infile;
	
	Student stu [MAX];
	

	appendR (infile, "sample.dat");

}

void appendR (fstream& infile, char filename [])
{
	infile.open (filename, ios::out | ios::app | ios::binary);
	
	if (!infile.good ())
	{
		cout<< "File not found" << endl;
		exit (1);
	}
	
	
	ofstream outfile ("sample.dat");
  	
	if (outfile.is_open())
  	{
    
	infile << "5\t" << "Thai\t" << "Pon_Mak\t" << "0.0\t" << "0.0\t" << "0.0\t" << "0.0\t"
	       << "0\t" << "Fail" << endl;
	
	  }
 
	infile.close();
	outfile.close();
}



sample.txt

1	British		David_Beckham	0.0	0.0 	0	Fail
2	Taiwanese	William_Ho	0.0	0.0	0	Fail
3	American	David_Howard	0.0	0.0	0	Fail
4	Malaysian	Mohd Sofian	0.0	0.0	0	Fail
Last edited on
Firstly, in your main you have fstream afile, but as a parameter to appendR for some reason you pass infile, that does not exist.
If you wish to append text, there is no need to open your file in binary mode.
After checking if the file was found simply use << operator to transmit whatever you need.

Also, is there any reason why you are using <cstring> rather than <string> ?
I still failed to append record. Instead of appending, I overwrite everything and left with 1 record.
If appending binary file, need to open in binary mode? No special reason with <string>.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
void appendR (fstream& infile, char filename []) {
    //why use binary mode.. your dealing with text files..
	infile.open (filename, ios::out | ios::app);

	if ( !infile.good() ) {
		cout<< "File not found" << endl;
		exit (1);
	}
    //you've open the file again here.. without appending flag..
	//ofstream outfile ("sample.dat", ios::out | ios::app | ios::binary);

	if (infile.is_open()) {
        infile << "5\t" << "Thai\t" << "Pon_Mak\t" << "0.0\t" << "0.0\t"
        << "0.0\t" << "0.0\t" << "0\t" << "Fail" << "\r\n";
        //use carriage return + linefeed if you're on windows..
    }
	infile.close();
	//outfile.close(); you don't need this anymore..
}
Topic archived. No new replies allowed.