check "fwrite" return value

Apr 24, 2011 at 6:22pm
my code is

fwrite(Head , sizeof(Student) , 1 , dat)
How I check if my allocation succeeded/fail?

Thanks in advance 4 all of you :)
Apr 24, 2011 at 6:45pm
http://www.cplusplus.com/reference/clibrary/cstdio/fwrite/
Return Value
The total number of elements successfully written is returned as a size_t object, which is an integral data type.
If this number differs from the count parameter, it indicates an error.
Apr 24, 2011 at 9:13pm
can you write it down in code please?
Apr 24, 2011 at 9:21pm
Check, using an if statement, if the size returned equals the number of elements, i.e. count parameter:

1
2
3
4
5
if (return_value != count)
{
   // an error

}

where, of course, you substitute for the italicised variables as appropriate, and add your error handling code inside the if block.
Apr 25, 2011 at 7:53am
I have a problam

1
2
3
4
fwrite(Head , sizeof(Student) , 1 , dat);	
if(size_t != count)
std::cout<<"The systerm did not succeeded saving your request"<<endl; 	
std::cout<<"The system absorbed your student"<<endl;	// check if the fwrite Succeed 


i'm getting an error "error C2059: syntax errer: '!="

what am I suppose to do ?
Apr 25, 2011 at 8:25am
I'm sorry. Perhaps I was not very clear. You don't have a variable called count. It is the third parameter of the fwrite function, in your case 1.

Further, size_t is a data type, like int (well, in a manner of speaking...). You want to get the return value of fwrite:
 
size_t return_value = fwrite(Head, sizeof(Student), 1, dat);


Then use an if statement to compare this return value and the count parameter.
Apr 25, 2011 at 8:32am
You are the KING !
Thank you !
Apr 25, 2011 at 8:45am
No problem. Do you now understand everything, and have your program working as you want it to?
Apr 25, 2011 at 9:53am
In fact yes, but I have another question...
The Visual studio created a binary file named data.dat (as I asked him to.. :) ) , can I take this file and open it in other program ?
I mean open a new project and load this "data.dat" ...?
Last edited on Apr 25, 2011 at 9:54am
Apr 25, 2011 at 10:15am
It's just a binary text file right? Then yes, you can open it in another program. But remember that it must be read in exactly the same way.

But, it is possibly the case that such a file would be problematic on another computer, where the format in memory of your class Student might be different.
Topic archived. No new replies allowed.