Question:
please tell me the problem in this c++ random file handling program?
j t
2009-01-09 09:18:33 UTC
i want to modify the roll numbers i have already stored.

#include
struct student
{
int roll;
};
void main()
{
int rol;
student st;
fstream file;
file.open("rollno.dat",ios::in|ios::out|ios::binary);
cout<<"enter the roll no to be modified";
cin>>rol;
while(file)
{
file.read((char*)&st,sizeof(student));
if(st.roll==rol)
{ cin>>st.roll; //new number
file.seekg(-1*sizeof(st),ios::cur);
file.write((char*)&st,sizeof(student));
}
}
file.seekg(0);
while(file)
{
file.read((char*)&st,sizeof(student));
cout<}
file.close();
}
Three answers:
JoelKatz
2009-01-09 09:49:35 UTC
I notice two specific issues with your program, but I'm not sure either of them is the main problem you're having. You don't describe what's not working, so it's hard to figure out what you specifically want fixed.



First, your while(file) loop outputs st.roll even if the read failed. This will result in the last number being output twice.



Second, you forgot to serialize the data before writing it. When you read from or write to a file, you need to specify the precise bytes you want write out and process the precise bytes you read in. Simply casting a 'student' to a 'char *' doesn't cut it.



For example, suppose you compile this on a computer that has four-byte integers and I compile it on a computer that has two-byte integers. One of us is not writing files in the correct format, and there's no way to know which of us. (Same argument goes for a big-endian versus a small-endian computer.)



You need to make a file format specification that specifies what bytes go where. (For example, if an integer is four bytes, do you write a 1 as 00-00-00-01 or 01-00-00-00?) Then you need to serialize your structure into that format.



Casting to write data to a file or socket is a *very* bad habit.
buddemeyer
2016-11-09 16:16:44 UTC
digital memory is a element of your problematical tension reserved for shifting "momentary" records. surely it particularly is prolonged RAM, you may advance/cut back this volume by going to My pc > residences > progressed > overall performance suggestions > progressed and seem on the form for "digital memory" this mistake can carry approximately a heavily decreased gadget overall performance, quite if multitasking, because of the fact the poster above suggested, i too recommend greater RAM, how plenty do you have now? (My pc > residences) the 1st element that comes up could desire to be the final tab, below which there's a heading pc: below that there will be a team of suggestion, seem for some thing like 256 RAM or 512 or 1gig (1024 megs)
tacolord455
2009-01-09 09:58:21 UTC
you also forgot #include

That is the library so you can use cout and cin


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...