C++ Files
Files
In C++ the library that holds the files is known as the file stream library. (#include <fstream.h>) The varying operating systems can handle certain features differently. Permitted file names vary. The 8 + 3 convention is normally safe to use:
- file names have 8 characters followed by
- optional full stop followed by
- optional 3 letter extension
Permitted characters:
- Roman alphabet (upper and lower case)
- underscore
- hyphen
- dollar sign
Upper and lower case are regarded as the same. Embedded systems can be more restrictive.
The fstream library contains several classes including:
- ifstream - input file stream
- ofstream - output file stream
- fstream - file stream. Both input and output. (NB - this class has the same name as the library)
The library iostream becomes available following #include <fstream.h>. This contains the cout file for writing to the screen and cin file for reading from the keyboard. Opening and closing of these files is automatic.
Insertion operator <<
int main(int argc, char* argv[])
{ //demonstrating the insertion operator <<
cout << "File stream input/output\n"; //Cursor moved to next line by \n
cout << 12345;
cout << true; //returns a 1
cout << 12345 << " File stream input/output\n"; //Combining insertions
getchar();
return 0;
}
Extraction operator >>
int main(int argc, char* argv[])
{
int Integer;
float Float;
cout << "File stream input/output - input\n";
cout << "Enter an integer, then press Enter: ";
cin >> Integer; //reads in integer from keyboard
cout << "\nYou entered: " << Integer << "\n";
getchar();
return 0;
}
Insertion/Extraction and strings
These present problems with string:
- Tab and initial space characters are ignored
- None space and none tab characters are read and stored until the first space/tab is encountered
Strings containing spaces cannot be read and stored using this method.
Comments, suggestions, ideas to
Stuart Banner
