7.0 File Streams
Getting information from different places is important. Until now, we’ve only gotten info from the iostream using cin and cout. Now, we’ll get info from text files using the file stream, using the fstream.h header. This works the same way as when we did the others, but instead of sending text and information to the screen, when you create a variable using the fstream, you send information to a file. Here’s an example of opening a file to read:
ifstream inData( “datafile.txt”, ios::in );
char tmpStr[40];
if ( !inData ){
cout << “whopse...couldn’t open \”datafile.txt\” for input.\n”;
exit( 1 );
}
while( inData > > tmpStr )
cout << tmpStr << “\n”;
File streams are created by the same method as any other variable, with “ifstream” as the variable type, and your name for the variable next (in our case, “inData”). The only difference is that ifstream’s are what is called an “object”; objects are declaired different than any other variable. (We’re not gonna go into objects just yet...just realize that you must declair filestreams a little different than any other variables).
The main thing about creating a file stream is that you are actually opening the file itself for editing, reading, appending, etc. You supply the name of the file you want to open or create, and then how you want to use the file. In the above case, we’re using the “in” mode, or “read only” mode. (If you’re curious, “ios” is apart of the iostream library. Its kinda complex, but basically, you’re telling the compiler, “go find ‘ios’ and give me the ‘in’ part). Technically, because “ifstream” is naturally a “in” object, you can leave out the “ios::in” part, and it will assume the rest, however, its always best to include that part, just to make sure. (ofstream’s are for outputting files).
Information is grabbed out of files the same way as standard cin and cout, by using the double arrows <<> > . The end of file is reached when no more data can be extracted; basically when it returns Zero. Since its returning zero or a huge number, you can test for it with a boolean operation, like “while( inData > > tmpStr )” and so forth.
7.1 The File Gotchyas
There are a few things to remember about filenames. Filenames are based upon the Operating System, and not the compiler. Window 3.1 will behave differently than WindowXP; and will behave differently than Linux. Know you’re filenames, play with spaces, paths and so forth.
7.2 Modes of Files
Here’s a list of ways to open up files:
ios::app Write all output to the end of the file.
ios::ate Open a file for output and move to the end of the file (normally used to append data to a file). Data can be written anywhere in the file
ios::in Open a file for input
ios::out Open a file for output
ios::trunc Discard the file’s contents if it exists (this is the default action for ios::out options)
ios::binary Open a file for non-text input or output.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment