Hello all,
I'm working on a file I/O at the moment and I need some guidance. I have a fraction structure, and I'm dynamically allocating the structure through the pointer as the user selects the option to add a fraction to the structure. After allocating the memory, and receiving the user input I have to store the fraction into a binary file. Here's my code so far as I've worked out.
My questions are :
1) Do I allocate memory then destroy the pointer after writing to the file ?
2) I'm not sure if I'm storing them correctly, as I have a run-time error when I try to display the fractions from the file. I tried using pointers to access it (did not work), and then after created a variable of type Fraction to try and access it. Both do not seem to work. It compiles and runs but when I try and display all the fractions using the read function, it goes into an infinite loop.
hi, i'm a bit of a beginner.
i've read your code and found some flaws that might be the cause:
1- inside the switch statement, you shouldn't open the file again before closing it, you've already opened the file in the declaration of your streams.
2-i think you should test if the file actually opened before using the stream, maybe your system is denying the program from creating the file from being created or accessed from the program, if this is the case, then i can't help convincing your system to let the program do its job.
these might be the cause of your problem, if you fix them and find other problems, i'll try to help.
Thank you very much @JLBorges. I actually had the sizeof(object) but, I had tried the ptr and probably copied that code over. Good to know.
I know this problem is much easier with formatted i/o but, our given problem states that we use binary files.
The really mind boggling fact is that we are required to use dynamic memory allocation. That is the sole reason I use a pointer instead of a variable of type Fraction. And, that is where I think where my main problem resides.
@Rechard3 Thank you for your suggestion. I'm a newbie myself and I'm trying to learn the ins and outs of file i/o. Now, that you mention it I do realize I shouldn't open the file again (and instead use one file stream for both input and output).
The system is creating the file as I can see it inside the executing folder. However, I'm not sure if the output is being written to the file in binary format.
@JLBorges Thank you very much. I never had thought of using a pointer to read the file stream ! This is the code I had been working on in the past 1 hour.
I'm sure it's rather bad coding. In the last three weeks we have been working on structures, pointers and finally files.
In the display statement, I was using the original Fraction type variable to access and it would just keep on showing random numbers.
We haven't covered vectors so, I'll have to figure out a different approach to solving it. I'll try out the code you have posted.
One last question :
I see you do