Module 2 - IO Streams and File IO
Module 2 - IO Streams and File IO
Pointers
▪ A pointer is simply a variable that holds a memory address.
▪ Declaration Syntax: data_type *var_name;
ip num (stored at 0x00367000)
▪ Example: Value Value
(0x00367000) 21
2 2
RMIT Classification: Trusted
▪ Array elements can be indexed using a pointer (array name is also a pointer to its first
element). Vice versa, a pointer can be also indexed as though it were an array.
char str[80] = "Hello World"; // Create a character array called str
char *p = str; // Declare and initialise a character pointer
str[4] = 'X'; //or *(str + 4) = 'X'; //replace the fourth element with 'X' character
*(p + 5) = 'Y'; //or p[5] = 'Y'; //replace the fifth space with 'Y' character
cout << str;
3 3
RMIT Classification: Trusted
//function definition
int max(int x, int y){ function max() is defined
return (x > y) ? x : y;
}
int main() {
int a, b, c, maxval;
cout << "Enter three integers: ";
cin >> a >> b >> c;
return 0;
}
5 5
RMIT Classification: Trusted
✓ Special case: a local static variable (declared with static keyword) maintain its value
between different function calls and exist until the program ends, like a global variable.
7
RMIT Classification: Trusted
▪ cerr: un-buffered standard error stream that is used to output the errors
(display the error message immediately).
▪ clog: buffered version of cerr (the message is first inserted into a buffer
before outputting until the buffer is fully filled or it is explicitly flushed). It is
used to output information to be logged (e.g. for later analysis)
Example:
set the required field width (minimum number of characters to be written) for
setw (int n)
displaying first next item that is output (effect disappear after that).
setfill (char c) specify the fill character to fill in the blank space (whenever using width()).
set precision for displaying any floating point value (maximum number of digits to
setprecision (int n)
be written).
resetiosflags() set a flag for formatting output (returns the previous value of format flag).
All stream manipulators above come from std namespace, and can be used without including <iomanip> header
RMIT University School of Science, Engineering and Technology (SSET) 14
RMIT Classification: Trusted
//Precision
Example cout << 3.14159 << " " << 12.3456 << " (DATA TO DISPLAY)\n";
cout << "precision = 3: \n";
cout << std::setprecision(3)
<< 3.14159 << " " << 12.3456 << "\n\n";
//Width
cout << 10 << " " << 20 << " (DATA TO DISPLAY)\n";
cout << "width = 10: \n";
cout << std::setw(10)
<< 10 << " " << 20 << "\n\n";
▪ In C++, files are mainly dealt by using following three classes available in
<fstream> header file.
o ofstream: allow you to open (or create) a file as an output stream. ie. WRITE
o Ifstream : allow you to open file as an input stream ie. READ
o fstream : allow you to open (or create) a file as
either an input or output stream. ie. Both READ/WRITE
void open (const char* Opens a file with given mode and filename, associating it with the stream object
filename, ios_base::openmode
mode)
void close() Closes the file currently associated with the object, disassociating it from the stream
(any pending output sequence is written to the file).
bool is_open() Return true if a file is open and associated with the stream object; false otherwise.
istream& get (char& c) Get character (extracts a single character from the stream). Returns reference to the
stream, or the end-of-file value (EOF) if no characters are available in the stream
ostream& put (char c); Put character (inserts character c into the stream). Returns reference to the stream
istream& read (char* s, Read block of data (extracts n characters from the stream and stores them in the
streamsize n); string array pointed to by s).
ostream& write (const char* s, Write block of data (inserts the first n characters of the string array pointed by s into
streamsize n); the stream).
istream& getline (char* s, Get a line. Extracts up to n - 1 characters from a line of the stream.
streamsize n );
bool eof() Return true if the End-of-File has been reached by the last operation; false otherwise.
RMIT University School of Science, Engineering and Technology (SSET) 17
RMIT Classification: Trusted
Opening a File
▪ A file must be opened before you can read from it or write to it
Mode Description
ios::app All output to the file is appended.
ios::ate Causes a seek to the end of the file i.e. the current location will be at the
end of the file when opened. I/O operations can however still occur
anywhere within the file.
ios::binary Opens file in binary mode. Data sent to the stream is what is exactly written
to the file. No text character or substitution takes place at any stage.
ios::in Open the file to READ from it
ios::out Create & Open the file to WRITE to it
ios::trunc Causes any existing file of the same name to be destroyed and the new file
to be zero length (overwrite any existing files of the same name)
▪ Reading from a File: we can use stream extraction operator (>>) with
ifstream or fstream object (instead of cin object for console input).
int main () {
//Create and open a file (use write mode only to create file).
std::fstream myfile;
and myfile.open("myFile.dat", std::ios::out);
if (!myfile) {
std::cerr << "Fail to create/open file \n";
reading }
return -1;
return 0;
}
RMIT University 20
RMIT Classification: Trusted
#include <iostream>
#include <fstream>
and Write }
/* Write to file */
to a file myfile << "Saving to file ..." << std::endl; //flush to write immediately
return 0;
}
22