Input/Output in C++
An Introduction |
Prof. David Bernstein |
Computer Science Department |
bernstdh@jmu.edu |
<iostream>
or
<fstream>
, rather than one of their parents
ifstream input_file; ofstream output_file;
System.in
and System.out
) you can use the streams
cin
and cout
<iostream>
:
cerr
clog
std::
)
or you need to include the
statement using namespace std;
std::cout << "Hi Mom! \n";
<<
and >>
are operators (more on them shortly)cin
is actually an object of type
istream_withassign
(which is a class that inherits
from istream
)cout
, cerr
, clog
are
actually objects of type ostream_withassign
(which is a class that inherits from ostream
)void open(const char *name, int mode)
void close(void)
name
is the name of the stream/filemode
is the I/O modeios
class):
ios::app | Open for append |
ios::ate | Go to the end |
ios::in | Open for input (required for ifstream) |
ios::out | Open for output (required for ofstream) |
ios::binary | Binary file |
ios::trunc | Discard existing contents |
ofstream output_file; output_file.open("sales.dat", (ios::out | ios::app | ios::nocreate) );
int bad() | Returns non-zero if the previous I/O operation failed and data were lost |
int good() | Returns non-zero if the previous I/O operation succeeded |
int eof() | Returns non-zero if previous read succeeded and the stream is empty |
int fail() | Returns non-zero if previous I/O operation failed |
<<
):
std::cout << "Go Dukes!";
int earnings; earnings = 10000; std::cout << "I earned " << earnings << " dollars this month";
>>
):
int orderNumber; cin >> orderNumber;
get | Extract a single character or a string (including whitespace) |
getline | Extract a full "line" of characters |
ignore | Discards a given number of characters |
putback | Inserts a character back into the input stream after it has been read |
/** * Splits the file test.txt into 10 or fewer pieces, * each containing 500 characters (except the last * piece which may be smaller) * * @author Prof. David Bernstein, James Madison University */ #include <iostream> #include <fstream> using namespace std; /** * fileSplit * * Reads a given file and splits it into pieces * containing a given number of characters * * @param inFileName[] The name of the input file * @param n The size of each piece */ void fileSplit(char inFileName[], int n) { char c; char outFileName[6] = { 'p', 'a', 'r', 't', '?', '\0' }; ifstream inFile; int characters, fileNumber; ofstream outFile; // Open the input file // inFile.open(inFileName, (ios::in)); if (inFile.fail()) { cout << "\tUnable to open input file!\n"; return; } // Initialize // characters = 0; fileNumber = 0; // Read in every character from the input file // (Note: Don't use << since it skips leading whitespace) // while (!inFile.eof()) { inFile.get(c); characters++; // Close the previous file if necessary // if (characters > n) { outFile.close(); fileNumber++; characters = 1; if (fileNumber >= 10) { cout << "\tToo many pieces!\n"; return; } } // Open the next file if necessary // if (characters == 1) { // Put the ASCII code into the output file name outFileName[4] = (fileNumber + 48); outFile.open(outFileName, ios::out); if (outFile.fail()) { cout << "\tUnable to open output file " << fileNumber << "!\n"; return; } } outFile.put(c); } inFile.close(); outFile.close(); } /** * main * * The entry point of the application */ int main(void) { fileSplit("test.txt", 500); return 1; }
setf(int flags)
unsetf(int flags)
ios
class):
ios::skipws | Skip leading whitespace on input |
ios::left | Left-justify output |
ios::right | Right-justify |
ios::internal | Pad between sign and number on output |
ios::dec | Output in base 10 |
ios::oct | Output in base 8 |
ios::hex | Output in base 16 |
ios::showbase | Include a base indicator on output |
ios::showpoint | Always include a decimal point n output |
ios::uppercase | For hexadecimal digits on output |
ios::showpos | Always include a + or - |
ios::scientific | Output in scientific notation |
ios::fixed | Output as fixed-point numbers |
using namespace std; cout.setf(ios::hex | ios::showbase | ios::uppercase ); cout << 1023;
0x3FF
<iomanip>
)
setiosflags(long flags) | Set the format bits |
resetiosflags(long flags) | Reset the format bits |
ws | Skip whitespace on input |
dec | Output in base 10 |
oct | Output in base 8 |
hex | Output in base 16 |
setw(int width | Set the width of the output |
setprecision(int precision) | Set the precision of floating point output |
setfill(char c) | Set the fill character |
endl | End of line (i.e., '\n') |
ends | End of string (i.e., '\0') |
#include <iostream> #include <iomanip> using namespace std; int n; n = 12; cout << setw(5) << n << "\n";
Three spaces and then the two-digit number 12
read
and write
methods:
inputFile.read(&n, sizeof(n));
sizeof
function returns the
size (in bytes) of its argument&
operator
provides the address of the variable n
(more on this later)short int
0x1234
consists of of two bytes (i.e., 0x12
and 0x34
). Some systems write the low-order byte first
(e.g., systems with Intel processors)
and others write the high-order byte first (e.g., systems with
Motorola 68000 processors).
seekg
seekp
inputFile.seekg(300);
Moves the read head to byte number 300
inputFile.seekg(-100, ios::end); inputFile.seekg(10, ios::cur);
First moves the read head to the position 100 bytes prior to the end of the file and then moves it 10 bytes forward from that position
tellg()
and tellp()
methods will
return the current position of the read and write heads,
respectively