c++ files

c++ files - Re ading and Writing to File in C s + I n m C...

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

View Full Document Right Arrow Icon
Reading and Writing to Files in C++ In many C++ programs we need to read and write data to a file on our computer. C++ provides special variables and functions that let you do this. To read or write data from/to a file: 1.First you must call a function to open the file. 2.Then you can call functions to read and write data from/to the file. 3.When you’re done, you must call a function to close the 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
To open a file, you must do the following: Reading and Writing to Files in C++ #include < fstream > A. Make sure to include fstream int main(void) { ifstream ifs ... } B. Declare an ifstream variable. ifs . open (“c:\\file.txt”, ios::in); C. Use the open function to open a file. D. Check to make sure there was not an error. if ( ! ifs ) { cout << “error: file not found”; return(-1); } Use ios::in to read from the file. Pass the name of the file to open first. Note : You can’t pass a C++ string to the open function. It will result in a syntax error. string fname = “foo.txt”; ifs.open( fname ,ios::in); // ERROR! : If you want to use a C++ string for the filename, you have to do this… string fname = “foo.txt”; ifs.open( fname.c_str() ,ios::in);
Background image of page 2
Here’s another way to open a file and read from it: Reading and Writing to Files in C++
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 05/11/2011 for the course CS 33 taught by Professor Rohr during the Spring '08 term at UCLA.

Page1 / 11

c++ files - Re ading and Writing to File in C s + I n m C...

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