上海交通大学交大密西根 联合学院·一 ◆ ■ 81T UM-SJTU Joint Institute University of Michigan Shanghal Jiao Tong University Reading from a file ·include<fstream> Declaration:ifstream inFile; Open and bundle it with a physical file on a disk: inFile.open ("InputData.dat"); Compiler will look for it from the same directory as the one where the project file resides. You can also use relative or absolute path: inFile.open("C:\leng101\hw\\hw6\hw6.dat");
Reading from a file Reading from a file • #include <fstream> • Declaration: ifstream inFile; • Open and bundle it with a physical file on a disk: inFile.open (“InputData.dat"); Compiler will look for it from the same directory as the one where the project file resides. • You can also use relative or absolute path: inFile.open("C:\\eng101\\hw\\hw6\\hw6.dat");
上海交通大学交大密西根 联合学院·一 ◆ 181 UM-SJTU Joint Institute University of Michigan Shanghal Jiao Tong University Reading from a file check for successfulness: if (inFile.fail())freturn true;} Read in the input stream. string name; int score; inFile >name > score; Close when you finished:inFile.close ()
Reading from a file Reading from a file • check for successfulness: if (inFile.fail()) {return true;} • Read in the input stream. string name; int score; inFile >> name >> score; • Close when you finished: inFile.close ();
上海交通大学交大密西根 ·联合学院一 181 UM-SJTU Joint Institute University of Michigan Shanghal Jiao Tong University Example for File Input #include <iostream> #include <Fstream> using namespace std; int main(void) ifstream inFile;/Create an input file object char fileName[26];/1D array of chars string name; Float score; cout <"What filename do you want to read from:" cin >fileName; inFile-open(fileName);//Connect the stream to the file if (!inFile.fail()) while (!infile.eof ()infile >name >score; cout <"End of input detected\n"; inFile.close();//Disconnect the stream from the file return 8;
Example for File Input Example for File Input
上海交通大学交大密西根 联合学院·一 ◆ 81T UM-SJTU Joint Institute ■ University of Michigan Shanghal Jiao Tong University Writing to a file Follow the same procedure with read in a file except changing the ifstream inFile;to ofstream outFile; and the direction of the data as indicated by the symbols >for input to <for output!
Writing to a file Writing to a file • Follow the same procedure with read in a file except changing the ifstream inFile; to ofstream outFile; and the direction of the data as indicated by the symbols >> for input to << for output!
上海交通大学交大密西根 ·联合学院一 181t UM-SJTU Joint Institute University of Michigan Shanghal Jiao Tong University Example for File Output int main(void) ifstrean inFile.open ("'InputFile.txt"'); ofstream outFile.open ("OutputFile.txt"'); string name; Float score; if (!inFile.fail()&outFile.fail()) while (!inFile.eof () inFile >name >score; outFile <name <<<score <endl; }; inFile.close(); outFile.close(); }; return 0;
Example for File Output Example for File Output