File I/O

Started by
2 comments, last by max621 24 years ago
Is there any place I can get a good tutorial on file I/O?? I''m intrested in both binary and text. I have been able to ouput single characters to a file: #include "stdio.h" #include "fstream.h" class CText{ public: int x; int y; int z; int r; int g; int b; char text[8]; }; void main () { fstream FioObject; char buf[256]; cout << "Enter some text\n"; cin >> buf; cout << "Text Saved\n"; FioObject.open("text.txt", ios::out); FioObject << buf; CText sometext; sometext.x=1; sometext.y=7; sometext.z=5; sometext.r=032; sometext.g=120; sometext.b=022; FioObject << sometext.x << sometext.y << sometext.z << sometext.r << sometext.z << sometext.g << sometext.b; FioObject << "Hello everybody"; }; So I know how to do text output with fstream, but what about with stdio? and how do I input? Thanks in advance.
||--------------------------||Black Hole Productionshttp://bhp.nydus.netResident expert on stuffmax621@barrysworld.com||--------------------------||
Advertisement
C++''s iostream library is mostly text oriented, and quite flexible. Binary file I/O is supported, but more limited than text. It can be a bit daunting as well

stdin and stdout are represented by the cin and cout objects, resp.

For reading from a file you can create a ifstream object. It''s opened as text as default. To read from it, use the >> operator.

If you want to read/write classes, overload the << and >> operator for the specific class. For example, for <<:

ostream& operator<<(ostream&, const Class&)
{ ... }

This function should be declared as a friend of the class you want to use it for. You can then write the class to an output stream like this:

Class c;
ofstream f("test.txt");
f << c;
cout << c;

The subject is really too large to discuss here in detail, so I suggest you get a good book on C++ that discusses the IOstream library. Maybe your IDE comes with help about the IOstream library.

Erik
http://homepages.go.com/~zatanik/ Check It...
Thanks for the help. I read the section on IO streams on Sams Teach Yourself.. c++..24 days on Informit.com
Its been a great help, and your direct writeing of classes is cool. Ill try it all out
||--------------------------||Black Hole Productionshttp://bhp.nydus.netResident expert on stuffmax621@barrysworld.com||--------------------------||

This topic is closed to new replies.

Advertisement