Cannot write struct data to a file

I am new to c++,and i am trying to do self learning..
I was creating a console member registration system.For that i used struct and
got input from the user to that struct and write that struct details to a text file.
Though inputs are written to the file they all are in unreadable manner..
I have used functions for writing and and viewing.mentioned error is under addrecord() function

//header declaration
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
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <conio.h>
#include <iomanip> 
#include <stdio.h>
#include <string.h>
#include <algorithm>
#include <string>
#include <fstream>

using namespace std;
int recsize;

struct member{
    string first_name[20], last_name[20];
    string spcl[100];
    int age,height,weight,memID,address;
    string ID[10];
	};

member e;  //struct member e also can be used


main(){
recsize = sizeof(e);
	string n;
	cout<<"Function occured"<<endl;
	FILE *fp, *ft;
        fp = fopen("users.txt","wb+");
        fseek(fp,0,SEEK_END);
       
                
                
                cout << "Enter the Firt Name : ";               
                cin >> e.first_name[20];
                cout << "Enter the Last Name : ";
                cin >> e.last_name[20];
                cout << "Enter the age    : ";
                cin >> e.age;
                cout << "Enter the Address   : ";
                cin >> e.address;
                fwrite(&e,recsize,1,fp);
                
            }
Last edited on
This looks like a huge mess. You've clearly been reading C code and you've created a horrible mish-mash of C and C++.

Your structure. I see that it contains an array of 20 strings named first_name. Are you really intending to store twenty first names in there? And your headers, what's going on with all those headers? Bleurgh. And conio.h? This is not the year 1990; if you want to learn C++ applicable to the present, seeing conio.h in any sample code you look at is a sign that you should simply delete it.

C++ gives you file writing capabilities. There's so much about your code that I don't like that frankly we're better off rewriting the whole thing, much more simply.

Here's some code that is much more C++. The struct object is responsible for writing itself to file, and it uses C++ file writing functions. Really, the structure should also be responsible for fetching information itself as well; perhaps in its constructor. I suggest you look at this code (which is much simpler than the previous code) and ask about anything you don't understand.

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
#include <iostream>
#include <string>
#include <fstream>

struct member{
  std::string first_name;
  std::string last_name;
  std::string spcl;
  int age,height,weight,memID,address;
  std::string ID;

  void writeToFile()
  {
    std::ofstream outputFile;
    outputFile.open("users.txt", std::ios::app);
    outputFile << first_name << " " << last_name << " " << age << " " << address << std::endl;
    outputFile.close();
  }
};

using std::cout;
using std::cin;


int main(){
  member e;
  cout << "Enter the Firt Name : "; 
  cin >> e.first_name;
  cout << "Enter the Last Name : ";
  cin >> e.last_name;
  cout << "Enter the age : ";
  cin >> e.age;
  cout << "Enter the Address : ";
  cin >> e.address;

  e.writeToFile();
}

Hey and welcome, please edit your code and use code tags, it makes it much easier to read - http://www.cplusplus.com/articles/jEywvCM9/

I don't think you are using structs the way you want to use them.

What you want a struct to hold is some information, in your case name age etc. Inside the struct you only need one of each, and then you create an array of that struct, rather than inside the struct creating an array of everything else.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
struct Person
{
   string name;
   int age;
}

int main()
{
    Person persons[10]; // Created 10 persons, each have a name and age
    
    persons[0].name = "Jennifer"; // First person
    persons[0].age = "19";
    
    persons[1].name = "blablabla"; // Accessing second person
}


Edit: Read post above
Last edited on
Thank you guys for u all great help..
i could send details to the text file,and view and search...
now again i have a problem how to update any content by asking which member with the mentioned last name should be edit...
i have tried it a bit,but couldn't make it...
code set used for updating is mentioned below
Again thank u all
i have used Moschops's code set for adding new records


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
//header declaration
#include <iostream>
#include <string>
#include <fstream>
#include <iomanip> 
#include <stdio.h>
#include <string.h>
#include <algorithm>
#include <string>

using namespace std;

char answer;


struct member{
  std::string first_name;
  std::string last_name;
  std::string spcl;
  int age,height,weight,memID,address;
  std::string ID;

  void writeToFile()
  {
    std::ofstream outputFile;
    outputFile.open("structchk.txt", std::ios::app);
    outputFile << memID <<" "<< first_name << " " << last_name << " " << age << " " << address << std::endl;
    outputFile.close();
  }
};
string xfirst_name, xlast_name;



member e;  //struct member e also can be used
int recsize = sizeof(e);

main(){

		FILE *fp;
		fp = fopen(structchk.txt"", "w");
	
          system("cls");
          another = 'Y';
          while (another == 'Y'|| another == 'y')
          {
              cout << "\n Enter the last name of the student : ";
              cin >> xlast_name;
 
            rewind(fp);
            while (fread(&e,recsize,1,fp) == 1)
            {
                if (strcmp(e.last_name,xlast_name) == 0)
                {
                cout << "Enter new the Firt Name : ";
                cin >> e.first_name;
                cout << "Enter new the Last Name : ";
                cin >> e.last_name;
                cout << "Enter new the Age    : ";
                cin >> e.age;
                cout << "Enter new the Address   : ";
                cin >> e.address;
                fseek(fp, - recsize, SEEK_CUR);
                fwrite(&e,recsize,1,fp);
                break;
                }
                else
                cout<<"record not found";
            }
            cout << "\n Modify Another Record (Y/N) ";
                fflush(stdin);
                another = getchar();
            }
	}
Last edited on
I could make a program which can write user details to files,search through those records and view all records.
and i want to modify that program to perform an update...
as i am new coding i can't figure out that..but i tried a bit..

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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
//header declaration
#include <iostream>
#include <cstdio>// same like iostream but can use old c libbries
#include <cstring>// same like string but older than string
#include <cstdlib>// inherited from c
#include <iomanip> 
#include <stdio.h>
#include <string.h>
#include <algorithm>
#include <string>
#include <fstream>

using namespace std;
void addrecord();     // function to add new members
void listrecord();    //function to view members as a table
void modifyrecord();  //function to update member details
void searchrecord();  //function to search member details

string username,password;
char another='y',answer;


struct member{
  std::string first_name;
  std::string last_name;
  std::string spcl;
  int age,height,weight,memID,address;
  std::string ID;

  void writeToFile()
  {
    std::ofstream outputFile;
    outputFile.open("structchk.txt", std::ios::app);
    outputFile << memID <<" "<< first_name << " " << last_name << " " << age << " " << address << std::endl;
    outputFile.close();
  }
};

string xfirst_name;
struct member cAMemberList[100];//Member array


member e;  //struct member e also can be used
int recsize = sizeof(e);

int main(){
	
	
	char attempt='y';
	char n;
     	cout << "\n\n";
     	cout << "\n \t\t\t 1. Add New Member details";
     	cout << "\n \t\t\t 2. View Members' table";
     	cout << "\n \t\t\t 3. Search Member details";
     	cout << "\n \t\t\t 4. Edit existing member details";
     	cout << "\n\n";
     	cout << "\t\t\t Select Your Choice :=> ";
     	fflush(stdin); 
     	cin>>n;// choice is for switch case
    	switch(n){
		case '1':
			addrecord();
			break;
		case '2':
			listrecord();
			break;
		case '3':
			searchrecord();
			break;
		case '4':
			modifyrecord();
			break;
	
			
		default:
			cout<<"ENTER VALID OPERATOR"<<endl;			
	}
    

}
void addrecord(){
	another ='Y';
	while(another == 'Y' || another == 'y')
	{
		system("cls");
		cout << "Enter the ID : ";
		cin >> e.memID;
		cout << "Enter the Firt Name : ";
		cin >> e.first_name;
		cout << "Enter the Last Name : ";
		cin >> e.last_name;
		cout << "Enter the age : ";
		cin >> e.age;
		cout << "Enter the Address : ";
		cin >> e.address;
		
		e.writeToFile();
		
		cout << "\n Add Another Record (Y/N) ";
		fflush(stdin);
		another = getchar();
    }
}
void listrecord(){
	system("cls");
	string line;
  	ifstream myfile ("structchk.txt");
  	if (myfile.is_open())
  	{
      while ( getline (myfile,line) )
      {
      cout << line << '\n';
    }
     myfile.close();
  }

  else cout << "Unable to open file"; 
            cout << "\n\n";
            system("pause");
	
}

void searchrecord(){
	
	ifstream fin;
	fin.open("structchk.txt");
	if(fin.fail())
	{
		cout << "Input file opening failed.\n";
		exit(1);
	}
	string search;
	cout << "Please enter a name: ";
	cin  >> search;
	bool isFound=0;
	while(!fin.eof())
	{
		string temp = "";
		getline(fin,temp);
		for(int i=0;i<search.size();i++)  //search.size is extracted material 
		{
			if(temp[i]==search[i])
				isFound = 1;
			else
			{
				isFound =0;
				break;
			}
		}

		if(isFound)
		{
			cout << "Details are: ";
			for(int i = search.size()+1;i<temp.size();i++)
				cout << temp[i];

			break;
		}

	}

	if(fin.eof()&&(!isFound))
	{
		cout << "Name not found!\n";
	}

	fin.close();
} 

void modifyrecord(){
	member e;
		string xlast_name;
		recsize=sizeof(e);
		FILE *fp;
		//outputFile.open("structchk.txt", std::ios::app);
		fp = fopen("structchk.txt", "wb+");
	
          system("cls");
          another = 'Y';
          while (another == 'Y'|| another == 'y')
          {
              cout << "\n Enter the last name of the student : ";
              cin >> xlast_name;
              const	char* a=e.last_name.c_str();
              const	char* b=xlast_name.c_str();
 
            rewind(fp);
            while (fread(&e,recsize,1,fp) == 1)
            {
             
                if (strcmp(a,b) == 1)//was0
                {
                cout << "Enter new the Firt Name : ";
                cin >> e.first_name;
                cout << "Enter new the Last Name : ";
                cin >> e.last_name;
                cout << "Enter new the Age    : ";
                cin >> e.age;
                cout << "Enter new the Address   : ";
                cin >> e.address;
                fseek(fp, - recsize, SEEK_CUR);
                fwrite(&e,recsize,1,fp);
                break;
                }
                else
                cout<<"record not found";
            }
            cout << "\n Modify Another Record (Y/N) ";
                fflush(stdin);
                another = getchar();
            }
	} 




Can anyone please tell me how to make this program to perform an update..
Last edited on
closed account (1vD3vCM9)
@Moschops

What alternatives ARE there for conio.h?
for now i do console applications to test stuff, and i use it instead of std::cin >> var
That conio.h is old not necessary for this program.
can handle the program with C++ library things

Stop using fseek, fwrite, and anything else you're getting out of a C programming textbook from the nineties. If you're going to use C++, then use C++.

Do not try to write bytes directly over the top of an existing file. All you could hope to do is replace some bytes with exactly the same number of bytes. Here's an example. imagine a file looks like this:

NAME_MICHAEL_AGE_36

and you wanted to change the name. So you find the beginning of MICHAEL and you replace it with the name JOHN. Now the file looks like this:

NAME_JOHNAEL_AGE_36

See the problem?

You can't just write over the top of the file. You have to read everything from it, write it all back again to a new file, and change the piece of data you want at the time of writing to the new file.
Last edited on
Thank you Moschops..

Can you show me a sample abt how to that..
i can't figure a way.. like to do searching that string
If you want to have a random access file your records need to have a fixed size.
Example:
1
2
3
4
5
6
7
struct member
{
  char first_name[20];
  char last_name[30];
  char spc[10]l;
  int age,height,weight,memID,address;
  char ID[20];

Then you can calculate the offset position of the file pointer with
 
int offset = sizeof(member) * RecordNumber;

It is then easy to set the file pointer and read / write individual records.

Here is a tutorial baout it:
http://www.eecs.umich.edu/courses/eecs380/HANDOUTS/cppBinaryFileIO-2.html
Topic archived. No new replies allowed.