I am facing problem with read and write functions in C++ and C also.
When I input 2 or more name
and id
s in my code it writes it perfectly to the file but when I read the file with fread
it show some weird behavior it prints same value of id
s as I enter for different inputs but for name it prints the same string for all inputs with different length which I entered last.
Example:
Input:
2
aaa 1
bbbb 2
Output:
ID 1 Name bbb
ID 2 Name bbbb
It should print like:
ID 1 Name aaa
ID 2 Name bbbb
My code:
#include <bits/stdc++.h>
using namespace std;
struct person
{
int id;
string fname;
};
int main () {
FILE *outfile;
struct person input;
int num,ident;
string sname;
outfile = fopen ("C:\\Users\\Amritesh\\Desktop\\students.txt","w+");
if (outfile == NULL)
{
fprintf(stderr, "\nError opend file\n");
exit (1);
}
scanf("%d",&num);
for(int i=0;i<num;i++){
cin >> sname;
scanf("%d",&ident);
struct person student = {ident,sname};
fwrite (&student, sizeof(struct person), 1, outfile);
}
fseek(outfile,0,SEEK_SET);
while(fread(&input, sizeof(struct person), 1, outfile)) {
cout << "ID " << input.id << " Name " <<input.fname << endl;
}
fclose (outfile);
return 0;
}
Thanks for any answer in advance.