{[ promptMessage ]}

Bookmark it

{[ promptMessage ]}

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 weneed 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 writedata from/to a file: 1.First you must call a function to open thefile. 2.Then you can call functions to read and write data from/to the file. 3.When you’redone, you must call a function to close thefile.
Background image of page 1

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

View Full Document Right Arrow Icon
To open a file, you must do the following: Reading and Writing to Files in C++ #include < fstream > A. Makesure to include fstream int main(void) { ifstream ifs ... } B. Declare an ifstream variable. ifs . open (“c:\\file.txt”, ios::in); C. Usethe open function to open a file. D. Check to make surethere was not an error. if ( ! ifs ) { cout << “error: file not found”; return(-1); } Use ios::in to read from the file. Pass the nameof the file to open first. Note : You can’t pass a C++ string to theopen 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 thefilename, 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
Background image of page 3

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

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

{[ snackBarMessage ]}