July 17th, 2003, 07:48 PM
Options for writing to files
I've got 4 c++ books and a reference book, but they still leave a lot to be desired. For some reason, I/O is just not covered very well. I've also been googling but haven't found all the answers I need yet.
I have a structure with 2 char arrays and an integer. What I'm trying to do is learn all the ways this structure can be written to a file.
I first tried the following example without the 'endl' commands but it wrote all the data on one line. I had expected ofstream to read and include the null terminators in the char arrays, but it doesn't? So I added them myself and it seemed to work fine.
I've also read some about write() and put(). Are these the only 3 methods available?
outfile << rec.first << endl << rec.second << endl << rec.num;
And could you give me a small example of how I would write the structure with write() and put() and which one of the 3 is preferable in various situations? Thanks.
July 17th, 2003, 08:22 PM
Hmmmm.... you seem like you want to output it on a text file and read it right? Then the thing you did was good for that.
But if you want to use the write() function I don't think it is readable (never looked). But lets say you wanted t save the whole struct:
seekp() puts the 'put' pointer at 0 bytes after the begining of the file.
write() needs the address of the 'thing' it wants to save (& address-of operator) , and needs to know how big that thing is.
I never used put() yet. But i think it might be for a single character or something like that.
EDIT: You said you had 4 bokks on C++ that didn't even explain those?!? Well my book is a free e-book. I'm about on chapter 21 (page 700 something) and it's really great! So go here http://www.uow.edu.au/~nabg/ABC/ABC.html download this book. And I suggest you skim through it quickly. (No need for part one. It only explains how a compter works. Incase you already know...)
Last edited by #define Gangsta; July 17th, 2003 at 08:27 PM.
July 17th, 2003, 11:31 PM
Thanks for the link. My books do cover I/O syntax, but the examples are too basic and don't cover very much. I don't think I've seen one example of writing structs and classes to files yet.
July 18th, 2003, 08:14 AM
The 'basic I/O' is ion chapter 9. And the 'advanced' with the write() and stuff is in chapter 17.