Lec23 - Lecture 23: File I/O PIC 10A Todd Wittman Sec 12.1:...

Info iconThis preview shows pages 1–4. Sign up to view the full content.

View Full Document Right Arrow Icon
1 Lecture 23: File I/O PIC 10A Todd Wittman Sec 12.1 : File Streams s Recall cin/cout are the I/O streams for the console window. s We can create our own I/O streams to read/write data different places. s In particular, we can create streams to read from and write to text files using the <fstream> library. s Declaring a stream is a lot like creating a variable. I like to call my file I/O streams fin & fout. (Other names work too!) ifstream fin; // A file input stream. ofstream fout; // A file output stream. s We can then use this stream to open a file and perform reading and writing procedures just like cin/cout. int x; fin >> x; //Read x from the file associated with fin. fout << x; //Write x to fout’s file, could be a different file.
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
2 A Basic Example s Write hello to the text file “out.txt”. #include <fstream> //Need the file I/O library. using namespace std; int main() { ofstream fout; //Create an output stream. fout.open(“out.txt"); //Open the file out.txt for writing. fout << "Hello Middle Earth!"; fout.close(); //Close the file when we’re done. return 0; } Opening Files s Suppose we want to read a list of integers in the text file “list.txt”. s The numbers could be separated by spaces or line breaks. s First we need to create the input stream and open the file for reading with this stream. ifstream fin; fin.open(“list.txt”); s This associates the file “list.txt” with fin. 42 15 -32 12 88 96 -12 2 33 44 -88 -22 37 2 1 0 1 2 3 list.txt
Background image of page 2
3 Opening Files s We could also have opened a file name given by the user. string file_name; cin >> file_name; ifstream fin; fin.open( file_name.c_str( ) ); s We add c_str( ) to convert the string to a char array. s We need this because open( ) is an older function that doesn’t recognize strings. Reading Files s To read the first #: int x; fin >> x; // Now x=42. s We can read the whole file with a loop and place the numbers in an array or vector. s If we don’t know how many numbers there are ahead of time, probably best to use a vector. s
Background image of page 3

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Image of page 4
This is the end of the preview. Sign up to access the rest of the document.

This note was uploaded on 11/19/2011 for the course PIC 10A taught by Professor Wittman during the Fall '08 term at UCLA.

Page1 / 9

Lec23 - Lecture 23: File I/O PIC 10A Todd Wittman Sec 12.1:...

This preview shows document pages 1 - 4. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online