Presentation is loading. Please wait.

Presentation is loading. Please wait.

Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba.

Similar presentations


Presentation on theme: "Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba."— Presentation transcript:

1 Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba

2 Starting Out with C++, 3 rd Edition 2 Chapter – File Operations

3 Starting Out with C++, 3 rd Edition 3 12.1 What is a File? A file is a collection on information, usually stored on a computer’s disk. Information can be saved to files and then later reused.

4 Starting Out with C++, 3 rd Edition 4 12.2 File Names All files are assigned a name that is used for identification purposes by the operating system and the user.

5 Starting Out with C++, 3 rd Edition 5 Table 12-1

6 Starting Out with C++, 3 rd Edition 6 12.3 Focus on Software Engineering: The Process of Using a File Using a file in a program is a simple three- step process –The file must be opened. If the file does not yet exits, opening it means creating it. –Information is then saved to the file, read from the file, or both. –When the program is finished using the file, the file must be closed.

7 Starting Out with C++, 3 rd Edition 7 Figure 12-1

8 Starting Out with C++, 3 rd Edition 8 Figure 12-2

9 Starting Out with C++, 3 rd Edition 9 12.4 Setting Up a Program for File Input/Output Before file I/O can be performed, a C++ program must be set up properly. File access requires the inclusion of fstream.h

10 Starting Out with C++, 3 rd Edition 10 12.5 Opening a File Before data can be written to or read from a file, the file must be opened. ifstream inputFile; inputFile.open(“customer.dat”); // Path of file using : ifstream fin("D:\\data.txt ");

11 Starting Out with C++, 3 rd Edition FLAGES IN FILE

12 Starting Out with C++, 3 rd Edition 12 // This program demonstrates the declaration of an fstream // object and the opening of a file. #include using namespace std; int main() { char x = 's'; int d = 77; double i = 3.14; ofstream fout("data.txt"); fout << x <<",“ << d<<",“ << ' ' << i ; fout.close(); cout << "File Completed\n";// in screen return 0; }

13 Starting Out with C++, 3 rd Edition // writing in file #include //divide by 7 #include using namespace std; int main() { ofstream fout("data.txt"); for(int i=4;i<=400;i++) if(i%7==0) //fout << i <<",“ << d<<",“ << ' ' << i ; fout<<i<<" : divide by Two (7)."<<"\n"; fout.close(); //cout<<i<<" : divide by Two (7)."<<"\n"; } 13

14 Starting Out with C++, 3 rd Edition #include // !x=x*(x-1)*(x-2)…. #include using namespace std; int main() { ofstream fout("factial.txt"); // Variable Declaration int counter, n, fact = 1; // Get Input Value cout<<"Enter the Number :"; cin>>n; //for Loop Block for (int counter = 1; counter <= n; counter++) { fact = fact * counter; } fout<<n<<" Factorial Value Is "<<fact; fout.close(); cout<<n<<" Factorial Value Is "<<fact; return 0; } 14

15 Starting Out with C++, 3 rd Edition #include >// !x=x*(x-1)*(x-2)…. Using function #include using namespace std; //Function long factorial(int); int main() { ofstream fout("flll.txt"); int counter, n; // Get Input Value cout<<"Enter the Number :"; cin>>n; // Factorial Function Call fout<<n<<" Factorial Value Is "<<factorial(n); cout<<n<<" Factorial Value Is "<<factorial(n); fout.close(); return 0; } // Factorial Function long factorial(int n) { int counter; long fact = 1; //for Loop Block for (int counter = 1; counter <= n; counter++) { fact = fact * counter; } return fact; } 15

16 Starting Out with C++, 3 rd Edition 16 Program Output with Example Input Enter the name of a file you wish to open or create: mystuff.dat [Enter] The file mystuff.dat was opened.

17 Starting Out with C++, 3 rd Edition 17 Table 12-3

18 Starting Out with C++, 3 rd Edition 18 Table 12-4

19 Starting Out with C++, 3 rd Edition 19 Table 12-4 continued

20 Starting Out with C++, 3 rd Edition 20 Opening a File at Declaration fstream dataFile(“names.dat”, ios::in | ios::out);

21 Starting Out with C++, 3 rd Edition 21 Program 12-2 // This program demonstrates the opening of a file at the // time the file stream object is declared. #include using namespace std; main( ) { fstream dataFile("names.txt", ios::in | ios::out); cout << "The file names.dat was opened.\n"; //system("PAUSE"); }

22 Starting Out with C++, 3 rd Edition 22 Program Output with Example Input The file names.dat was opened.

23 Starting Out with C++, 3 rd Edition 23 Testing for Open Errors dataFile.open(“cust.txt”, ios::in); if (!dataFile) { cout << “Error opening file.\n”; }

24 Starting Out with C++, 3 rd Edition 24 Another way to Test for Open Errors dataFile.open(“cust.dat”, ios::in); if (dataFile.fail()) { cout << “Error opening file.\n”; }

25 Starting Out with C++, 3 rd Edition 25 12.6 Closing a File A file should be closed when a program is finished using it.

26 Starting Out with C++, 3 rd Edition // writing on a text file #include using namespace std; int main () { ofstream myfile ("example.txt"); if (myfile.is_open()) { myfile << "This is a new file created in cpp.\n"; myfile << "This is another line.\n"; myfile.close(); } else cout << "Unable to open file"; system("pause"); return 0; }

27 Starting Out with C++, 3 rd Edition // reading a text file #include using namespace std; int main () { string line; ifstream myfile ("example.txt"); if (myfile.is_open()) { while ( getline (myfile,line) ) { cout << line << endl; } myfile.close(); } else cout << "Unable to open file"; system("pause"); return 0; }

28 Starting Out with C++, 3 rd Edition file operations in C++ #include using namespace std; int main () { ofstream myfile; myfile.open ("example22.txt"); myfile << "Writing this to a file.\n"; myfile<<"Hope fine”" << endl; myfile<<"this frist file ”" << endl; myfile.close(); system("pause"); return 0; } Slide 6- 28

29 Starting Out with C++, 3 rd Edition #include using namespace std; int main() { char FirstName[30], LastName[30]; int Age; char FileName[20]; cout << "Enter First Name: "; cin >> FirstName; cout << "Enter Last Name: "; cin >> LastName; cout << "Enter Age: "; cin >> Age; cout << "\nEnter the name of the file you want to create: "; cin >> FileName; ofstream Students(FileName, ios::out); Students << FirstName << "\n" << LastName << "\n" << Age; cout << "\n\n"; return 0; } Slide 6- 29

30 Starting Out with C++, 3 rd Edition // basic file operations #include using namespace std; int main () { ofstream myfile; myfile.open ("example.txt"); myfile << "Writing this to a file.\n"; myfile.close(); system("pause"); return 0; } Slide 6- 30

31 Starting Out with C++, 3 rd Edition Write to file #include int main() { ofstream fout; fout.open("D:\\firstExa.txt"); fout << "Asalamualikom hope fine.\n" << "WELCOME TO GE 211 FILE SECTION PROGRAM\n" << "HOPE TO DO WELL IN SECOND MEDTERM EXAM\n"; fout.close(); system("pause"); }

32 Starting Out with C++, 3 rd Edition //Write the odd number in file #include int main() { ofstream fout; fout.open("D:\\firstExa.txt"); int i,j; for(i=2;i<30;i+=2) fout<<i<<"\t"; fout.close(); system("pause"); }

33 Starting Out with C++, 3 rd Edition // print in file Even number 1:30 #include int main() { ofstream fout; fout.open("D:\\firstExa.txt"); int i,j; for(i=1;i<30;i+=2) fout<<i<<"\t"; fout.close(); system("pause"); }

34 Starting Out with C++, 3 rd Edition #include main() {ofstream fout; fout.open("D:\\ffffff.txt"); float i,j,m,sum; j=3; sum=0; for(i=1;i<=100;i++){ m=(i*i)/(j*j); j=j+2; sum=sum+m;} cout<<"seque="<<sum<<endl; fout<<"seque="<<sum<<endl; fout.close(); system("pause");}

35 Starting Out with C++, 3 rd Edition //write equation for this series #include main() { int i,j,m,n,sum; sum=0; cin>>n; for(i=1 ;i<=n ;i++) { m=i*i; sum=sum+m; } cout<< "seque="<<sum<< endl; system("pause"); }

36 Starting Out with C++, 3 rd Edition #include main() { float i,m,n,b,a,y,x,s; y=0; b=2; cout<<"enter the last power of\n"; cin>>n; cout<<"enter the volue of(x)\n"; cin>>s; for(i=1;i<=n;i++){ x=pow(s,i); a=pow(b,i); m=x/a; y=y+m; } cout<<"y= "<<y; system("pause"); }

37 Starting Out with C++, 3 rd Edition #include main() {ofstream fout; fout.open("D:\\UUUU.txt"); float i,m,n,b,a,y,x,s; y=0; b=2; cout<<"enter the last power of\n"; cin>>n; cout<<"enter the volue of(x)\n"; cin>>s; for(i=1;i<=n;i++){ x=pow(s,i); a=pow(b,i); m=x/a; y=y+m; } cout<<"y= "<<y; fout<<"y= "<<y; fout.close(); system("pause"); }

38 Starting Out with C++, 3 rd Edition //Fenonci seris #include main() {ofstream fout; fout.open("D:\\finoncy.txt"); int i,s,b,d ; s=0; d=1; for(i=0;i<20;i++) { b=s; s=d; d=s+b; fout<<d<<"\t"; } fout.close(); system("pause");}

39 Starting Out with C++, 3 rd Edition //write to file #include main() { ofstream fout; fout.open("D:\\Seris.txt"); int i,j,m,n,sum; sum=0; cin>>n; for(i=1 ;i<=n ;i++) { m=i*i; sum=sum+m; } fout<< "seque="<<sum<< endl; fout.close(); system("pause"); }

40 Starting Out with C++, 3 rd Edition Read from file #include main() { char array [80]; ifstream fin; fin.open("D:\\firstExa.txt"); while(!fin.eof()) {fin.getline(array,80); cout<<array<<endl;} fin.close(); system("pause"); }

41 Starting Out with C++, 3 rd Edition FLAGES IN FILE

42 Starting Out with C++, 3 rd Edition Write in binary file ofstream fout ; fout.open("file path",iostream family fout.write((char*)& data,sizeo(data);

43 Starting Out with C++, 3 rd Edition Binary form #include main() { int Array[80],i; for(i=0;i<10;i++) cin>> Array[i]; ofstream fout; fout.open("D:\\ahmed.bin",ios::binary); fout.write((char *) & Array, sizeof(Array)); fout.close(); system("pause"); }

44 Starting Out with C++, 3 rd Edition // writing on a text file #include using namespace std; int main () { ofstream myfile ("example.txt"); if (myfile.is_open()) { myfile << "This is a line.\n"; myfile << "This is another line.\n"; myfile.close(); } else cout << "Unable to open file"; system("pause"); return 0; } Slide 6- 44

45 Starting Out with C++, 3 rd Edition // reading a text file #include using namespace std; int main () { string line; ifstream myfile ("example.txt"); if (myfile.is_open()) { while ( myfile.good() ) { getline (myfile,line); cout << line << endl; } myfile.close(); } else cout << "Unable to open file"; system("pause"); return 0; } Slide 6- 45

46 Starting Out with C++, 3 rd Edition Slide 6- 46 I/O Streams I/O refers to program input and output –Input is delivered to your program via a stream object –Input can be from The keyboard A file –Output is delivered to the output device via a stream object –Output can be to The screen A file

47 Starting Out with C++, 3 rd Edition Using fout Slide 6- 47 #include using namespace std; int main (int aaa,char *avg[]) { ofstream fout ("my_out.txt"); fout<<" Assalamualikom Hope fine" << endl; fout<<"Please tray good in second exam this frist file " << endl; system("pause"); return 0;}

48 Starting Out with C++, 3 rd Edition Write in file #include using namespace std; int main( ) { //cout<<"Exam1\n"; // ifstream ;// read // ofstream ;// write // fstream;//read &write ofstream myfile; myfile.open("kkkk.txt"); myfile<< "Exam1 is ok\n"; myfile<< "please tray good in second exam"; myfile.close(); system("pause"); return 0; }

49 Starting Out with C++, 3 rd Edition Using fstream #include using namespace std; int main( ) { /*cout<<"Exam1\n"; // ifstream ;// read // ofstream ;// write // fstream;//read &write*/ fstream myfile; myfile.open("kkkk.txt",ios ::out); //myfile<< "Exam1 is ok\n"; myfile<< "please tray good in second exam****************"; //cout<<myfile.rdbuf(); myfile.close(); system("pause"); return 0; }

50 Starting Out with C++, 3 rd Edition Using app #include using namespace std; int main( ) { /*cout<<"Exam1\n"; ifstream ;// read ofstream ;// write fstream;//read &write*/ fstream myfile; myfile.open("kkkk.txt",ios ::out|ios::app); //myfile<< "Exam1 is ok\n"; myfile<< "please tray good in second exam****************\n"; //cout<<myfile.rdbuf(); myfile.close(); system("pause"); return 0; }

51 Starting Out with C++, 3 rd Edition Read from file #include using namespace std; int main( ) { /*cout<<"Exam1\n"; ifstream ;// read ofstream ;// write fstream;//read &write*/ ifstream myfile; myfile.open("kkkk.txt"); //myfile<< "Exam1 is ok\n"; //myfile<< "please tray good in second exam"; cout<<myfile.rdbuf(); myfile.close(); system("pause"); return 0; }

52 Starting Out with C++, 3 rd Edition Input &Output with files Input / Output with files C++ provides the following classes to perform output and input of characters to/from files: ofstream: Stream class to write on files ifstream: Stream class to read from files fstream: Stream class to both read and write from/to files.

53 Starting Out with C++, 3 rd Edition // basic file operations #include using namespace std; int main () { ofstream myfile; myfile.open ("example.txt"); myfile << "Writing this to a file.\n"; myfile.close(); return 0; }

54 Starting Out with C++, 3 rd Edition classdefault mode parameter ofstreamios::out ifstreamios::in fstreamios::in | ios::out ofstream myfile; myfile.open ("example.bin", ios::out | ios::app | ios::binary);

55 Starting Out with C++, 3 rd Edition Basic file operations // basic file operations #include //#include using namespace std; int main () { ofstream myfile; myfile.open ("XXX.txt"); myfile << "**Writing this to a file.\n"; myfile << "****Writing this to a file.\n"; myfile << "*********Writing this to a file.\n"; myfile.close(); system("PAUSE"); return 0; }

56 Starting Out with C++, 3 rd Edition Basic file operations #include using namespace std; int main (int argc, char *arvg[ ]) { ofstream fout("XXX.txt"); fout << "**Writing this to a file.\n"; fout << "****Writing this to a file.\n"; fout << "*********Writing this to a file.\n"; system("PAUSE"); return EXIT_SUCCESS; }

57 Starting Out with C++, 3 rd Edition FILE IN C++ ios::inOpen for input operations. ios::outOpen for output operations. ios::binaryOpen in binary mode. ios::ate Set the initial position at the end of the file. If this flag is not set to any value, the initial position is the beginning of the file. ios::app All output operations are performed at the end of the file, appending the content to the current content of the file. This flag can only be used in streams open for output-only operations. ios::trunc If the file opened for output operations already existed before, its previous content is deleted and replaced by the new one.

58 Starting Out with C++, 3 rd Edition // writing on a text file #include using namespace std; int main () { ofstream myfile ("example.txt"); if (myfile.is_open()) { myfile << "This is a line.\n"; myfile << "This is another line.\n"; myfile.close(); } else cout << "Unable to open file"; return 0; }

59 Starting Out with C++, 3 rd Edition Open a file The first operation generally performed on an object of one of these classes is to associate it to a real file. This procedure is known as to open a file. An open file is represented within a program by a stream object (an instantiation of one of these classes, in the previous example this was myfile) and any input or output operation performed on this stream object will be applied to the physical file associated to it. In order to open a file with a stream object we use its member function open(): open (filename, mode); Where filename is a null-terminated character sequence of type const char * (the same type that string literals have) representing the name of the file to be opened, and mode is an optional parameter with a combination of the following flags:

60 Starting Out with C++, 3 rd Edition

61

62 IOS :: IN OPEN FILE FOR READ

63 Starting Out with C++, 3 rd Edition

64

65 65 Program 12-3 // This program demonstrates the close function. #include void main(void) { fstream dataFile; dataFile.open("testfile.txt", ios::out); if (!dataFile) { cout << "File open error!" << endl; return; } cout << "File was created successfully.\n"; cout << "Now closing the file.\n"; dataFile.close(); }

66 Starting Out with C++, 3 rd Edition 66 Program Output File was created successfully. Now closing the file.

67 Starting Out with C++, 3 rd Edition 67 12.7 Using << to Write Information to a File The stream insertion operator (<<) may be used to write information to a file. outputFile << “I love C++ programming !”

68 Starting Out with C++, 3 rd Edition 68 Program 12-4 // This program uses the << operator to write information to a file. #include void main(void) { fstream dataFile; char line[81]; dataFile.open("demofile.txt", ios::out); if (!dataFile) { cout << "File open error!" << endl; return; }

69 Starting Out with C++, 3 rd Edition 69 Program continues cout << "File opened successfully.\n"; cout << "Now writing information to the file.\n"; dataFile << "Jones\n"; dataFile << "Smith\n"; dataFile << "Willis\n"; dataFile << "Davis\n"; dataFile.close(); cout << "Done.\n"; }

70 Starting Out with C++, 3 rd Edition 70 Program Screen Output File opened successfully. Now writing information to the file. Done. Output to File demofile.txt Jones Smith Willis Davis

71 Starting Out with C++, 3 rd Edition 71 Figure 12-3

72 Starting Out with C++, 3 rd Edition 72 Program 12-5 // This program writes information to a file, closes the file, // then reopens it and appends more information. #include void main(void) { fstream dataFile; dataFile.open("demofile.txt", ios::out); dataFile << "Jones\n"; dataFile << "Smith\n"; dataFile.close(); dataFile.open("demofile.txt", ios::app); dataFile << "Willis\n"; dataFile << "Davis\n"; dataFile.close(); }

73 Starting Out with C++, 3 rd Edition 73 Output to File demofile.txt Jones Smith Willis Davis

74 Starting Out with C++, 3 rd Edition 74 12.8 File Output Formatting File output may be formatted the same way as screen output.

75 Starting Out with C++, 3 rd Edition 75 Program 12-6 // This program uses the precision member function of a // file stream object to format file output. #include void main(void) { fstream dataFile; float num = 123.456; dataFile.open("numfile.txt", ios::out); if (!dataFile) { cout << "File open error!" << endl; return; }

76 Starting Out with C++, 3 rd Edition 76 Program continues dataFile << num << endl; dataFile.precision(5); dataFile << num << endl; dataFile.precision(4); dataFile << num << endl; dataFile.precision(3); dataFile << num << endl; }

77 Starting Out with C++, 3 rd Edition 77 Contents of File numfile.txt 123.456 123.46 123.5 124

78 Starting Out with C++, 3 rd Edition 78 Program 12-7 #include void main(void) {fstream outFile("table.txt", ios::out); int nums[3][3] = { 2897, 5, 837, 34, 7, 1623, 390, 3456, 12 }; // Write the three rows of numbers for (int row = 0; row < 3; row++) { for (int col = 0; col < 3; col++) { outFile << setw(4) << nums[row][col] << " "; } outFile << endl; } outFile.close(); }

79 Starting Out with C++, 3 rd Edition 79 Contents of File TABLE.TXT 2897 5 837 34 7 1623 390 3456 12

80 Starting Out with C++, 3 rd Edition 80 Figure 12-6

81 Starting Out with C++, 3 rd Edition 81 12.9 Using >> to Read Information from a File The stream extraction operator (>>) may be used to read information from a file.

82 Starting Out with C++, 3 rd Edition 82 Program 12-8 // This program uses the >> operator to read information from a file. #include void main(void) { fstream dataFile; char name[81]; dataFile.open("demofile.txt", ios::in); if (!dataFile) { cout << "File open error!" << endl; return; } cout << "File opened successfully.\n"; cout << "Now reading information from the file.\n\n";

83 Starting Out with C++, 3 rd Edition 83 Program continues for (int count = 0; count < 4; count++) { dataFile >> name; cout << name << endl; } dataFile.close(); cout << "\nDone.\n"; }

84 Starting Out with C++, 3 rd Edition 84 Program Screen Output File opened successfully. Now reading information from the file. Jones Smith Willis Davis Done.

85 Starting Out with C++, 3 rd Edition 85 12.10 Detecting the End of a File The eof() member function reports when the end of a file has been encountered. if (inFile.eof()) inFile.close();

86 Starting Out with C++, 3 rd Edition 86 Program 12-9 // This program uses the file stream object's eof() member // function to detect the end of the file. #include void main(void) { fstream dataFile; char name[81]; dataFile.open("demofile.txt", ios::in); if (!dataFile) { cout << "File open error!" << endl; return; } cout << "File opened successfully.\n"; cout << "Now reading information from the file.\n\n";

87 Starting Out with C++, 3 rd Edition 87 Program continues dataFile >> name; // Read first name from the file while (!dataFile.eof()) { cout << name << endl; dataFile >> name; } dataFile.close(); cout << "\nDone.\n"; }

88 Starting Out with C++, 3 rd Edition 88 Program Screen Output File opened successfully. Now reading information from the file. Jones Smith Willis Davis Done.

89 Starting Out with C++, 3 rd Edition 89 Note on eof() In C++, “end of file” doesn’t mean the program is at the last piece of information in the file, but beyond it. The eof() function returns true when there is no more information to be read.

90 Starting Out with C++, 3 rd Edition 90 12.11 Passing File Stream Objects to Functions File stream objects may be passed by reference to functions. bool openFileIn(fstream &file, char name[51]) { bool status; file.open(name, ios::in); if (file.fail()) status = false; else status = true; return status; }

91 Starting Out with C++, 3 rd Edition 91 12.12 More Detailed Error Testing All stream objects have error state bits that indicate the condition of the stream.

92 Starting Out with C++, 3 rd Edition 92 Table 12-5

93 Starting Out with C++, 3 rd Edition 93 Table 12-6

94 Starting Out with C++, 3 rd Edition 94 Program 12-11 // This program demonstrates the return value of the stream // object error testing member functions. #include // Function prototype void showState(fstream &); void main(void) { fstream testFile("stuff.dat", ios::out); if (testFile.fail()) { cout << "cannot open the file.\n"; return; }

95 Starting Out with C++, 3 rd Edition 95 Program continues int num = 10; cout << "Writing to the file.\n"; testFile << num;// Write the integer to testFile showState(testFile); testFile.close();// Close the file testFile.open("stuff.dat", ios::in);// Open for input if (testFile.fail()) { cout << "cannot open the file.\n"; return; }

96 Starting Out with C++, 3 rd Edition 96 Program continues cout << "Reading from the file.\n"; testFile >> num;// Read the only number in the file showState(testFile); cout << "Forcing a bad read operation.\n"; testFile >> num;// Force an invalid read operation showState(testFile); testFile.close();// Close the file } // Definition of function ShowState. This function uses // an fstream reference as its parameter. The return values of // the eof(), fail(), bad(), and good() member functions are // displayed. The clear() function is called before the function // returns.

97 Starting Out with C++, 3 rd Edition 97 Program continues void showState(fstream &file) { cout << "File Status:\n"; cout << " eof bit: " << file.eof() << endl; cout << " fail bit: " << file.fail() << endl; cout << " bad bit: " << file.bad() << endl; cout << " good bit: " << file.good() << endl; file.clear();// Clear any bad bits }

98 Starting Out with C++, 3 rd Edition 98 Program Output Writing to the file. File Status: eof bit: 0 fail bit: 0 bad bit: 0 good bit: 1 Reading from the file. File Status: eof bit: 0 fail bit: 0 bad bit: 0 good bit: 1 Forcing a bad read operation. File Status: eof bit: 1 fail bit: 2 bad bit: 0 good bit: 0

99 Starting Out with C++, 3 rd Edition 99 12.13 Member Functions for Reading and Writing Files File stream objects have member functions for more specialized file reading and writing.

100 Starting Out with C++, 3 rd Edition 100 Figure 12-8

101 Starting Out with C++, 3 rd Edition 101 Program 12-12 // This program uses the file stream object's eof() member // function to detect the end of the file. #include void main(void) { fstream nameFile; char input[81]; nameFile.open("murphy.txt", ios::in); if (!nameFile) { cout << "File open error!" << endl; return; }

102 Starting Out with C++, 3 rd Edition 102 Program 12-12 (continued) nameFile >> input; while (!nameFile.eof()) { cout << input; nameFile >> input; } nameFile.close(); }

103 Starting Out with C++, 3 rd Edition 103 Program Screen Output JayneMurphy47JonesCircleAlmond,NC28702

104 Starting Out with C++, 3 rd Edition 104 The getline Member Function dataFile.getline(str, 81, ‘\n’); str – This is the name of a character array, or a pointer to a section of memory. The information read from the file will be stored here. 81 – This number is one greater than the maximum number of characters to be read. In this example, a maximum of 80 characters will be read. ‘\n’ – This is a delimiter character of your choice. If this delimiter is encountered, it will cause the function to stop reading before it has read the maximum number of characters. (This argument is optional. If it’s left our, ‘\n’ is the default.)

105 Starting Out with C++, 3 rd Edition 105 Program 12-13 // This program uses the file stream object's getline member // function to read a line of information from the file. #include void main(void) { fstream nameFile; char input[81]; nameFile.open("murphy.txt", ios::in); if (!nameFile) { cout << "File open error!" << endl; return; }

106 Starting Out with C++, 3 rd Edition 106 Program continues nameFile.getline(input, 81); // use \n as a delimiter while (!nameFile.eof()) { cout << input << endl; nameFile.getline(input, 81); // use \n as a delimiter } nameFile.close(); }

107 Starting Out with C++, 3 rd Edition 107 Program Screen Output Jayne Murphy 47 Jones Circle Almond, NC 28702

108 Starting Out with C++, 3 rd Edition 108 Program 12-14 // This file shows the getline function with a user- // specified delimiter. #include void main(void) { fstream dataFile("names2.txt", ios::in); char input[81]; dataFile.getline(input, 81, '$'); while (!dataFile.eof()) { cout << input << endl; dataFile.getline(input, 81, '$'); } dataFile.close(); }

109 Starting Out with C++, 3 rd Edition 109 Program Output Jayne Murphy 47 Jones Circle Almond, NC 28702 Bobbie Smith 217 Halifax Drive Canton, NC 28716 Bill Hammet PO Box 121 Springfield, NC 28357

110 Starting Out with C++, 3 rd Edition 110 The get Member Function inFile.get(ch);

111 Starting Out with C++, 3 rd Edition 111 Program 12-15 // This program asks the user for a file name. The file is // opened and its contents are displayed on the screen. #include void main(void) { fstream file; char ch, fileName[51]; cout << "Enter a file name: "; cin >> fileName; file.open(fileName, ios::in); if (!file) { cout << fileName << “ could not be opened.\n"; return; }

112 Starting Out with C++, 3 rd Edition 112 Program continues file.get(ch); // Get a character while (!file.eof()) { cout << ch; file.get(ch); // Get another character } file.close(); }

113 Starting Out with C++, 3 rd Edition 113 The put Member Function outFile.put(ch);

114 Starting Out with C++, 3 rd Edition 114 Program 12-16 // This program demonstrates the put member function. #include void main(void) {fstream dataFile("sentence.txt", ios::out); char ch; cout << "Type a sentence and be sure to end it with a "; cout << "period.\n"; while (1) { cin.get(ch); dataFile.put(ch); if (ch == '.') break; } dataFile.close(); }

115 Starting Out with C++, 3 rd Edition 115 Program Screen Output with Example Input Type a sentence and be sure to end it with a period. I am on my way to becoming a great programmer. [Enter] Resulting Contents of the File SENTENCE.TXT: I am on my way to becoming a great programmer.

116 Starting Out with C++, 3 rd Edition 116 12.14 Focus on Software Engineering: Working with Multiple Files It’s possible to have more than one file open at once in a program.

117 Starting Out with C++, 3 rd Edition 117 Program 12-17 // This program demonstrates reading from one file and writing // to a second file. #include #include // Needed for the toupper function void main(void) { ifstream inFile; ofstream outFile("out.txt"); char fileName[81], ch, ch2; cout << "Enter a file name: "; cin >> fileName; inFile.open(fileName); if (!inFile) { cout << "Cannot open " << fileName << endl; return; }

118 Starting Out with C++, 3 rd Edition 118 Program continues inFile.get(ch); // Get a characer from file 1 while (!inFile.eof()) // Test for end of file { ch2 = toupper(ch); // Convert to uppercase outFile.put(ch2); // Write to file2 inFile.get(ch); // Get another character from file 1 } inFile.close(); outFile.close(); cout << "File conversion done.\n"; }

119 Starting Out with C++, 3 rd Edition 119 Program Screen Output with Example Input Enter a file name: hownow.txt [Enter] File conversion done. Contents of hownow.txt: how now brown cow. How Now? Resulting Contents of out.txt: HOW NOW BROWN COW. HOW NOW?

120 Starting Out with C++, 3 rd Edition 120 12.15 Binary Files Binary files contain data that is unformatted, and not necessarily stored as ASCII text. file.open(“stuff.dat”, ios::out | ios::binary);

121 Starting Out with C++, 3 rd Edition 121 Figure 12-9

122 Starting Out with C++, 3 rd Edition 122 Figure 12-10

123 Starting Out with C++, 3 rd Edition 123 Program 12-18 // This program uses the write and read functions. #include void main(void) { fstream file(“NUMS.DAT", ios::out | ios::binary); int buffer[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; cout << "Now writing the data to the file.\n"; file.write((char*)buffer, sizeof(buffer)); file.close(); file.open("NUMS.DAT", ios::in); // Reopen the file. cout << "Now reading the data back into memory.\n"; file.read((char*)buffer, sizeof(buffer)); for (int count = 0; count < 10; count++) cout << buffer[count] << " "; file.close(); }

124 Starting Out with C++, 3 rd Edition 124 Program Screen Output Now writing the data to the file. Now reading the data back into memory. 1 2 3 4 5 6 7 8 9 10

125 Starting Out with C++, 3 rd Edition 125 12.16 Creating Records with Structures Structures may be used to store fixed-length records to a file. struct Info { char name[51]; int age; char address1[51]; char address2[51]; char phone[14]; }; Since structures can contain a mixture of data types, you should always use the ios::binary mode when opening a file to store them.

126 Starting Out with C++, 3 rd Edition 126 Program 12-19 // This program demonstrates the use of a structure variable to // store a record of information to a file. #include #include // for toupper // Declare a structure for the record. struct Info { char name[51]; int age; char address1[51]; char address2[51]; char phone[14]; };

127 Starting Out with C++, 3 rd Edition 127 Program continues void main(void) { fstream people("people.dat", ios::out | ios::binary); Info person; char again; if (!people) { cout << "Error opening file. Program aborting.\n"; return; } do { cout << "Enter the following information about a ” << "person:\n"; cout << "Name: ";

128 Starting Out with C++, 3 rd Edition 128 Program continues cin.getline(person.name, 51); cout << "Age: "; cin >> person.age; cin.ignore(); // skip over remaining newline. cout << "Address line 1: "; cin.getline(person.address1, 51); cout << "Address line 2: "; cin.getline(person.address2, 51); cout << "Phone: "; cin.getline(person.phone, 14); people.write((char *)&person, sizeof(person)); cout << "Do you want to enter another record? "; cin >> again; cin.ignore(); } while (toupper(again) == 'Y'); people.close(); }

129 Starting Out with C++, 3 rd Edition 129 Program Screen Output with Example Input Enter the following information about a person: Name: Charlie Baxter [Enter] Age: 42 [Enter] Address line 1: 67 Kennedy Bvd. [Enter] Address line 2: Perth, SC 38754 [Enter] Phone: (803)555-1234 [Enter] Do you want to enter another record? Y [Enter] Enter the following information about a person: Name: Merideth Murney [Enter] Age: 22 [Enter] Address line 1: 487 Lindsay Lane [Enter] Address line 2: Hazelwood, NC 28737 [Enter] Phone: (704)453-9999 [Enter] Do you want to enter another record? N [Enter]

130 Starting Out with C++, 3 rd Edition 130 12.17 Random Access Files Random Access means non-sequentially accessing informaiton in a file. Figure 12-11

131 Starting Out with C++, 3 rd Edition 131 Table 12-7

132 Starting Out with C++, 3 rd Edition 132 Table 12-8

133 Starting Out with C++, 3 rd Edition 133 Program 12-21 // This program demonstrates the seekg function. #include void main(void) { fstream file("letters.txt", ios::in); char ch; file.seekg(5L, ios::beg); file.get(ch); cout << "Byte 5 from beginning: " << ch << endl; file.seekg(-10L, ios::end); file.get(ch); cout << "Byte 10 from end: " << ch << endl;

134 Starting Out with C++, 3 rd Edition 134 Program continues file.seekg(3L, ios::cur); file.get(ch); cout << "Byte 3 from current: " << ch << endl; file.close(); }

135 Starting Out with C++, 3 rd Edition 135 Program Screen Output Byte 5 from beginning: f Byte 10 from end: q Byte 3 from current: u

136 Starting Out with C++, 3 rd Edition 136 The tellp and tellg Member Functions tellp returns a long integer that is the current byte number of the file’s write position. tellg returns a long integer that is the current byte number of the file’s read position.

137 Starting Out with C++, 3 rd Edition 137 Program 12-23 // This program demonstrates the tellg function. #include #include // For toupper void main(void) { fstream file("letters.txt", ios::in); long offset; char ch, again; do { cout << "Currently at position " << file.tellg() << endl; cout << "Enter an offset from the beginning of the file: "; cin >> offset;

138 Starting Out with C++, 3 rd Edition 138 Program continues file.seekg(offset, ios::beg); file.get(ch); cout << "Character read: " << ch << endl; cout << "Do it again? "; cin >> again; } while (toupper(again) == 'Y'); file.close(); }

139 Starting Out with C++, 3 rd Edition 139 Program Output with Example Input Currently at position 0 Enter an offset from the beginning of the file: 5 [Enter] Character read: f Do it again? y [Enter] Currently at position 6 Enter an offset from the beginning of the file: 0 [Enter] Character read: a Do it again? y [Enter] Currently at position 1 Enter an offset from the beginning of the file: 20 [Enter] Character read: u Do it again? n [Enter]

140 Starting Out with C++, 3 rd Edition 140 12.18 Opening a File for Both Input and Output You may perform input and output on an fstream file without closing it and reopening it. fstream file(“data.dat”, ios::in | ios::out);

141 Starting Out with C++, 3 rd Edition 141 Program 12-24 // This program sets up a file of blank inventory records. #include // Declaration of Invtry structure struct Invtry { char desc[31]; int qty; float price; }; void main(void) { fstream inventory("invtry.dat", ios::out | ios::binary); Invtry record = { "", 0, 0.0 };

142 Starting Out with C++, 3 rd Edition 142 Program continues // Now write the blank records for (int count = 0; count < 5; count++) { cout << "Now writing record " << count << endl; inventory.write((char *)&record, sizeof(record)); } inventory.close(); }

143 Starting Out with C++, 3 rd Edition 143 Program Screen Output Now writing record 0 Now writing record 1 Now writing record 2 Now writing record 3 Now writing record 4

144 Starting Out with C++, 3 rd Edition 144 Program 12-25 // This program displays the contents of the inventory file. #include // Declaration of Invtry structure struct Invtry { char desc[31]; int qty; float price; }; void main(void) { fstream inventory("invtry.dat", ios::in | ios::binary); Invtry record = { "", 0, 0.0 };

145 Starting Out with C++, 3 rd Edition 145 Program continues // Now read and display the records inventory.read((char *)&record, sizeof(record)); while (!inventory.eof()) { cout << "Description: "; cout << record.desc << endl; cout << "Quantity: "; cout << record.qty << endl; cout << "Price: "; cout << record.price << endl << endl; inventory.read((char *)&record, sizeof(record)); } inventory.close(); }

146 Starting Out with C++, 3 rd Edition 146 Here is the screen output of Program 12-25 if it is run immediately after Program 12-24 sets up the file of blank records. Program Screen Output Description: Quantity: 0 Price: 0.0 Description: Quantity: 0 Price: 0.0 Description: Quantity: 0 Price: 0.0 Description: Quantity: 0 Price: 0.0 Description: Quantity: 0 Price: 0.0

147 Starting Out with C++, 3 rd Edition 147 Program 12-26 // This program allows the user to edit a specific record in // the inventory file. #include // Declaration of Invtry structure struct Invtry { char desc[31]; int qty; float price; }; void main(void) {

148 Starting Out with C++, 3 rd Edition 148 Program continues fstream inventory("invtry.dat", ios::in | ios::out | ios::binary); Invtry record; long recNum; cout << "Which record do you want to edit?"; cin >> recNum; inventory.seekg(recNum * sizeof(record), ios::beg); inventory.read((char *)&record, sizeof(record)); cout << "Description: "; cout << record.desc << endl; cout << "Quantity: "; cout << record.qty << endl; cout << "Price: "; cout << record.price << endl; cout << "Enter the new data:\n"; cout << "Description: ";

149 Starting Out with C++, 3 rd Edition 149 Program continues cin.ignore(); cin.getline(record.desc, 31); cout << "Quantity: "; cin >> record.qty; cout << "Price: "; cin >> record.price; inventory.seekp(recNum * sizeof(record), ios::beg); inventory.write((char *)&record, sizeof(record)); inventory.close(); }

150 Starting Out with C++, 3 rd Edition 150 Program Screen Output with Example Input Which record do you ant to edit? 2 [Enter] Description: Quantity: 0 Price: 0.0 Enter the new data: Description: Wrench [Enter] Quantity: 10 [Enter] Price: 4.67 [Enter]

151 Starting Out with C++, 3 rd Edition

152 Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 6 I/O Streams as an Introduction to Objects and Classes

153 Starting Out with C++, 3 rd Edition Slide 6- 153 Overview 6.1 Streams and Basic File I/O 6.2 Tools for Stream I/O 6.3 Character I/O

154 Starting Out with C++, 3 rd Edition Copyright © 2008 Pearson Addison-Wesley. All rights reserved. 6.1 Streams and Basic File I/O

155 Starting Out with C++, 3 rd Edition Slide 6- 155 I/O Streams I/O refers to program input and output –Input is delivered to your program via a stream object –Input can be from The keyboard A file –Output is delivered to the output device via a stream object –Output can be to The screen A file

156 Starting Out with C++, 3 rd Edition Slide 6- 156 Objects Objects are special variables that –Have their own special-purpose functions –Set C++ apart from earlier programming languages

157 Starting Out with C++, 3 rd Edition Slide 6- 157 Streams and Basic File I/O Files for I/O are the same type of files used to store programs A stream is a flow of data. –Input stream: Data flows into the program If input stream flows from keyboard, the program will accept data from the keyboard If input stream flows from a file, the program will accept data from the file –Output stream: Data flows out of the program To the screen To a file

158 Starting Out with C++, 3 rd Edition Slide 6- 158 cin And cout Streams cin –Input stream connected to the keyboard cout –Output stream connected to the screen cin and cout defined in the iostream library –Use include directive: #include You can declare your own streams to use with files.

159 Starting Out with C++, 3 rd Edition Slide 6- 159 Why Use Files? Files allow you to store data permanently! Data output to a file lasts after the program ends An input file can be used over and over –No typing of data again and again for testing Create a data file or read an output file at your convenience Files allow you to deal with larger data sets

160 Starting Out with C++, 3 rd Edition Slide 6- 160 File I/O Reading from a file –Taking input from a file –Done from beginning to the end (for now) No backing up to read something again (OK to start over) Just as done from the keyboard Writing to a file –Sending output to a file –Done from beginning to end (for now) No backing up to write something again( OK to start over) Just as done to the screen

161 Starting Out with C++, 3 rd Edition Slide 6- 161 Stream Variables Like other variables, a stream variable… –Must be declared before it can be used –Must be initialized before it contains valid data Initializing a stream means connecting it to a file The value of the stream variable can be thought of as the file it is connected to –Can have its value changed Changing a stream value means disconnecting from one file and connecting to another

162 Starting Out with C++, 3 rd Edition Slide 6- 162 Streams and Assignment A stream is a special kind of variable called an object –Objects can use special functions to complete tasks Streams use special functions instead of the assignment operator to change values

163 Starting Out with C++, 3 rd Edition Slide 6- 163 Declaring An Input-file Stream Variable Input-file streams are of type ifstream Type ifstream is defined in the fstream library –You must use the include and using directives #include using namespace std; Declare an input-file stream variable using ifstream in_stream;

164 Starting Out with C++, 3 rd Edition Slide 6- 164 Declaring An Output-file Stream Variable Ouput-file streams of are type ofstream Type ofstream is defined in the fstream library –You must use these include and using directives #include using namespace std; Declare an input-file stream variable using ofstream out_stream;

165 Starting Out with C++, 3 rd Edition Slide 6- 165 Once a stream variable is declared, connect it to a file –Connecting a stream to a file is opening the file –Use the open function of the stream object in_stream.open("infile.dat"); Period File name on the disk Double quotes Connecting To A File

166 Starting Out with C++, 3 rd Edition Slide 6- 166 Using The Input Stream Once connected to a file, the input-stream variable can be used to produce input just as you would use cin with the extraction operator –Example: int one_number, another_number; in_stream >> one_number >> another_number;

167 Starting Out with C++, 3 rd Edition Slide 6- 167 Using The Output Stream An output-stream works similarly to the input-stream –ofstream out_stream; out_stream.open("outfile.dat"); out_stream << "one number = " << one_number << "another number = " << another_number;

168 Starting Out with C++, 3 rd Edition Slide 6- 168 External File Names An External File Name… –Is the name for a file that the operating system uses infile.dat and outfile.dat used in the previous examples –Is the "real", on-the-disk, name for a file –Needs to match the naming conventions on your system –Usually only used in the stream's open statement –Once open, referred to using the name of the stream connected to it.

169 Starting Out with C++, 3 rd Edition After using a file, it should be closed –This disconnects the stream from the file –Close files to reduce the chance of a file being corrupted if the program terminates abnormally It is important to close an output file if your program later needs to read input from the output file The system will automatically close files if you forget as long as your program ends normally Slide 6- 169 Display 6.1 Closing a File

170 Starting Out with C++, 3 rd Edition Slide 6- 170 Objects An object is a variable that has functions and data associated with it –in_stream and out_stream each have a function named open associated with them –in_stream and out_stream use different versions of a function named open One version of open is for input files A different version of open is for output files

171 Starting Out with C++, 3 rd Edition Slide 6- 171 Member Functions A member function is a function associated with an object –The open function is a member function of in_stream in the previous examples –A different open function is a member function of out_stream in the previous examples

172 Starting Out with C++, 3 rd Edition Slide 6- 172 Objects and Member Function Names Objects of different types have different member functions –Some of these member functions might have the same name Different objects of the same type have the same member functions

173 Starting Out with C++, 3 rd Edition Slide 6- 173 Classes A type whose variables are objects, is a class –ifstream is the type of the in_stream variable (object) –ifstream is a class –The class of an object determines its member functions –Example: ifstream in_stream1, in_stream2; in_stream1.open and in_stream2.open are the same function but might have different arguments

174 Starting Out with C++, 3 rd Edition Slide 6- 174 Class Member Functions Member functions of an object are the member functions of its class The class determines the member functions of the object –The class ifstream has an open function –Every variable (object) declared of type ifstream has that open function

175 Starting Out with C++, 3 rd Edition Slide 6- 175 Calling object Dot operator Member function Calling a Member Function Calling a member function requires specifying the object containing the function The calling object is separated from the member function by the dot operator Example: in_stream.open("infile.dat");

176 Starting Out with C++, 3 rd Edition Slide 6- 176 Member Function Calling Syntax Syntax for calling a member function: Calling_object.Member_Function_Name(Argument_list);

177 Starting Out with C++, 3 rd Edition Slide 6- 177 Errors On Opening Files Opening a file could fail for several reasons –Common reasons for open to fail include The file might not exist The name might be typed incorrectly May be no error message if the call to open fails –Program execution continues!

178 Starting Out with C++, 3 rd Edition Slide 6- 178 Catching Stream Errors Member function fail, can be used to test the success of a stream operation –fail returns a boolean type (true or false) –fail returns true if the stream operation failed

179 Starting Out with C++, 3 rd Edition Slide 6- 179 Halting Execution When a stream open function fails, it is generally best to stop the program The function exit, halts a program –exit returns its argument to the operating system –exit causes program execution to stop –exit is NOT a member function Exit requires the include and using directives #include using namespace std;

180 Starting Out with C++, 3 rd Edition Immediately following the call to open, check that the operation was successful: in_stream.open("stuff.dat"); if( in_stream.fail( ) ) { cout << "Input file opening failed.\n"; exit(1) ; } Slide 6- 180 Display 6.2 Using fail and exit

181 Starting Out with C++, 3 rd Edition Slide 6- 181 Techniques for File I/O When reading input from a file… –Do not include prompts or echo the input The lines cout > the_number; cout > the_number; –The input file must contain exactly the data expected

182 Starting Out with C++, 3 rd Edition Output examples so far create new files –If the output file already contains data, that data is lost To append new output to the end an existing file –use the constant ios::app defined in the iostream library: outStream.open("important.txt", ios::app); –If the file does not exist, a new file will be created Slide 6- 182 Display 6.3 Appending Data (optional)

183 Starting Out with C++, 3 rd Edition Slide 6- 183 File Names as Input (optional) Program users can enter the name of a file to use for input or for output Program must use a variable that can hold multiple characters –A sequence of characters is called a string –Declaring a variable to hold a string of characters: char file_name[16]; file_name is the name of a variable Brackets enclose the maximum number of characters + 1 The variable file_name contains up to 15 characters

184 Starting Out with C++, 3 rd Edition char file_name[16]; cout > file_name; ifstream in_stream; in_stream.open(file_name); if (in_stream.fail( ) ) { cout << "Input file opening failed.\n"; exit(1); } Slide 6- 184 Display 6.4 (1) Display 6.4 (2) Using A Character String

185 Starting Out with C++, 3 rd Edition Slide 6- 185 Section 6.1 Conclusion Can you –Write a program that uses a stream called fin which will be connected to an input file and a stream called fout which will be connected to an output file? How do you declare fin and fout? What include directive, if any, do you nee to place in your program file? –Name at least three member functions of an iostream object and give examples of usage of each?

186 Starting Out with C++, 3 rd Edition Copyright © 2008 Pearson Addison-Wesley. All rights reserved. 6.2 Tools for Streams I/O

187 Starting Out with C++, 3 rd Edition Slide 6- 187 Tools for Stream I/O To control the format of the program's output –We use commands that determine such details as: The spaces between items The number of digits after a decimal point The numeric style: scientific notation for fixed point Showing digits after a decimal point even if they are zeroes Showing plus signs in front of positive numbers Left or right justifying numbers in a given space

188 Starting Out with C++, 3 rd Edition Slide 6- 188 Formatting Output to Files Format output to the screen with: cout.setf(ios::fixed); cout.setf(ios::showpoint); cout.precision(2); Format output to a file using the out-file stream named out_stream with: out_stream.setf(ios::fixed); out_stream.setf(ios::showpoint); out_stream.precision(2);

189 Starting Out with C++, 3 rd Edition Slide 6- 189 out_stream.precision(2); precision is a member function of output streams –After out_stream.precision(2); Output of numbers with decimal points… will show a total of 2 significant digits 23.2.2e7 2.2 6.9e-10.00069 OR will show 2 digits after the decimal point 23.562.26e7 2.21 0.690.69e-4 Calls to precision apply only to the stream named in the call

190 Starting Out with C++, 3 rd Edition Slide 6- 190 setf(ios::fixed); setf is a member function of output streams –setf is an abbreviation for set flags A flag is an instruction to do one of two options ios::fixed is a flag –After out_stream.setf(ios::fixed); All further output of floating point numbers… Will be written in fixed-point notation, the way we normally expect to see numbers Calls to setf apply only to the stream named in the call

191 Starting Out with C++, 3 rd Edition After out_stream.setf(ios::showpoint); Output of floating point numbers… Will show the decimal point even if all digits after the decimal point are zeroes Slide 6- 191 Display 6.5 setf(ios::showpoint);

192 Starting Out with C++, 3 rd Edition Slide 6- 192 7 7 (ios::right) (ios::left) Creating Space in Output The width function specifies the number of spaces for the next item –Applies only to the next item of output Example: To print the digit 7 in four spaces use out_stream.width(4); out_stream << 7 << endl; –Three of the spaces will be blank

193 Starting Out with C++, 3 rd Edition Slide 6- 193 Not Enough Width? What if the argument for width is too small? –Such as specifying cout.width(3); when the value to print is 3456.45 The entire item is always output –If too few spaces are specified, as many more spaces as needed are used

194 Starting Out with C++, 3 rd Edition Slide 6- 194 Unsetting Flags Any flag that is set, may be unset Use the unsetf function –Example: cout.unsetf(ios::showpos); causes the program to stop printing plus signs on positive numbers

195 Starting Out with C++, 3 rd Edition Slide 6- 195 Manipulators A manipulator is a function called in a nontraditional way –Manipulators in turn call member functions –Manipulators may or may not have arguments –Used after the insertion operator (<<) as if the manipulator function call is an output item

196 Starting Out with C++, 3 rd Edition Slide 6- 196 Two SpacesFour Spaces The setw Manipulator setw does the same task as the member function width –setw calls the width function to set spaces for output Example: cout << "Start" << setw(4) << 10 << setw(4) << setw(6) << 30; produces: Start 10 20 30

197 Starting Out with C++, 3 rd Edition Slide 6- 197 The setprecision Manipulator setprecision does the same task as the member function precision Example: cout.setf(ios::fixed); cout.setf(ios::showpoint); cout << "$" << setprecision(2) << 10.3 << endl << "$" << 20.5 << endl; produces: $10.30 $20.50 –setprecision setting stays in effect until changed

198 Starting Out with C++, 3 rd Edition Slide 6- 198 Manipulator Definitions The manipulators setw and setprecision are defined in the iomanip library –To use these manipulators, add these lines #include using namespace std;

199 Starting Out with C++, 3 rd Edition Slide 6- 199 Stream Names as Arguments Streams can be arguments to a function –The function's formal parameter for the stream must be call-by-reference Example: void make_neat(ifstream& messy_file, ofstream& neat_file);

200 Starting Out with C++, 3 rd Edition Slide 6- 200 The End of The File Input files used by a program may vary in length –Programs may not be able to assume the number of items in the file A way to know the end of the file is reached: –The boolean expression (in_stream >> next) Reads a value from in_stream and stores it in next True if a value can be read and stored in next False if there is not a value to be read (the end of the file)

201 Starting Out with C++, 3 rd Edition Slide 6- 201 End of File Example To calculate the average of the numbers in a file – double next, sum = 0; int count = 0; while(in_stream >> next) { sum = sum + next; count++; } double average = sum / count;

202 Starting Out with C++, 3 rd Edition Slide 6- 202 Stream Arguments and Namespaces Using directives have been local to function definitions in the examples so far When parameter type names are in a namespace –A using directive must be outside the function so C++ will understand the parameter type names such as ifstream Easy solution is to place the using directive at the beginning of the file –Many experts do not approve as this does not allow using multiple namespaces with names in common

203 Starting Out with C++, 3 rd Edition The program in Display 6.6… –Takes input from rawdata.dat –Writes output to the screen and to neat.dat Formatting instructions are used to create a neater layout Numbers are written one per line in a field width of 12 Each number is written with 5 digits after the decimal point Each number is written with a plus or minus sign –Uses function make_neat that has formal parameters for the input-file stream and output-file stream Slide 6- 203 Display 6.6 (1)Display 6.6 (2)Display 6.6 (3) Program Example

204 Starting Out with C++, 3 rd Edition Slide 6- 204 Section 6.2 Conclusion Can you –Show the output produced when the following line is executed? cout << "*" << setw(3) << 12345 << "*" endl; –Describe the effect of each of these flags? Ios::fixed ios::scientificios::showpoint ios::rightios::rightios::showpos

205 Starting Out with C++, 3 rd Edition Copyright © 2008 Pearson Addison-Wesley. All rights reserved. 6.3 Character I/O

206 Starting Out with C++, 3 rd Edition Slide 6- 206 Character I/O All data is input and output as characters –Output of the number 10 is two characters '1' and '0' –Input of the number 10 is also done as '1' and '0' –Interpretation of 10 as the number 10 or as characters depends on the program –Conversion between characters and numbers is usually automatic

207 Starting Out with C++, 3 rd Edition Slide 6- 207 Low Level Character I/O Low level C++ functions for character I/O –Perform character input and output –Do not perform automatic conversions –Allow you to do input and output in anyway you can devise

208 Starting Out with C++, 3 rd Edition Slide 6- 208 Member Function get Function get –Member function of every input stream –Reads one character from an input stream –Stores the character read in a variable of type char, the single argument the function takes –Does not use the extraction operator (>>) which performs some automatic work –Does not skip blanks

209 Starting Out with C++, 3 rd Edition Slide 6- 209 Using get These lines use get to read a character and store it in the variable next_symbol char next_symbol; cin.get(next_symbol); –Any character will be read with these statements Blank spaces too! '\n' too! (The newline character)

210 Starting Out with C++, 3 rd Edition Slide 6- 210 get Syntax input_stream.get(char_variable); Examples: char next_symbol; cin.get(next_symbol); ifstream in_stream; in_stream.open("infile.dat"); in_stream.get(next_symbol);

211 Starting Out with C++, 3 rd Edition Slide 6- 211 More About get Given this code:char c1, c2, c3; cin.get(c1); cin.get(c2); cin.get(c3); and this input: AB CD c1 = 'A' c2 = 'B' c3 = '\n' –cin >> c1 >> c2 >> c3; would place 'C' in c3 (the ">>" operator skips the newline character)

212 Starting Out with C++, 3 rd Edition Slide 6- 212 The End of The Line To read and echo a line of input – Look for '\n' at the end of the input line: cout<<"Enter a line of input and I will " << "echo it.\n"; char symbol; do { cin.get(symbol); cout << symbol; } while (symbol != '\n'); –All characters, including '\n' will be output

213 Starting Out with C++, 3 rd Edition Slide 6- 213 '\n ' vs "\n " '\n' –A value of type char –Can be stored in a variable of type char "\n" –A string containing only one character –Cannot be stored in a variable of type char In a cout-statement they produce the same result

214 Starting Out with C++, 3 rd Edition Slide 6- 214 Member Function put Function put –Member function of every output stream –Requires one argument of type char –Places its argument of type char in the output stream –Does not do allow you to do more than previous output with the insertion operator and cout

215 Starting Out with C++, 3 rd Edition Slide 6- 215 put Syntax Output_stream.put(Char_expression); Examples: cout.put(next_symbol); cout.put('a'); ofstream out_stream; out_stream.open("outfile.dat"); out_stream.put('Z');

216 Starting Out with C++, 3 rd Edition Slide 6- 216 Member Function putback The putback member function places a character in the input stream –putback is a member function of every input stream –Useful when input continues until a specific character is read, but you do not want to process the character –Places its argument of type char in the input stream –Character placed in the stream does not have to be a character read from the stream

217 Starting Out with C++, 3 rd Edition Slide 6- 217 putback Example The following code reads up to the first blank in the input stream fin, and writes the characters to the file connected to the output stream fout –fin.get(next); while (next != ' ') { fout.put(next); fin.get(next); } fin.putback(next); –The blank space read to end the loop is put back into the input stream

218 Starting Out with C++, 3 rd Edition Slide 6- 218 Program Example Checking Input Incorrect input can produce worthless output Use input functions that allow the user to re-enter input until it is correct, such as –Echoing the input and asking the user if it is correct –If the input is not correct, allow the user to enter the data again

219 Starting Out with C++, 3 rd Edition Slide 6- 219 Checking Input:get_int The get_int function seen in Display 6.7 obtains an integer value from the user –get_int prompts the user, reads the input, and displays the input –After displaying the input, get_int asks the user to confirm the number and reads the user's response using a variable of type character –The process is repeated until the user indicates with a 'Y' or 'y' that the number entered is correct

220 Starting Out with C++, 3 rd Edition The new_line function seen in Display 6.7 is called by the get_int function –new_line reads all the characters remaining in the input line but does nothing with them, essentially discarding them –new_line is used to discard what follows the first character of the the user's response to get_line's "Is that correct? (yes/no)" The newline character is discarded as well Slide 6- 220 Display 6.7 (1) Display 6.7 (2) Checking Input:new_line

221 Starting Out with C++, 3 rd Edition Slide 6- 221 Checking Input: Check for Yes or No? get_int continues to ask for a number until the user responds 'Y' or 'y' using the do-while loop do { // the loop body } while ((ans !='Y') &&(ans != 'y') ) Why not use ((ans =='N') | | (ans == 'n') )? –User must enter a correct response to continue a loop tested with ((ans =='N') | | (ans == 'n') ) What if they mis-typed "Bo" instead of "No"? –User must enter a correct response to end the loop tested with ((ans !='Y') &&(ans != 'y') )

222 Starting Out with C++, 3 rd Edition Slide 6- 222 Mixing cin >> and cin.get Be sure to deal with the '\n' that ends each input line if using cin >> and cin.get –"cin >>" reads up to the '\n' –The '\n' remains in the input stream –Using cin.get next will read the '\n' –The new_line function from Display 6.7 can be used to clear the '\n'

223 Starting Out with C++, 3 rd Edition Slide 6- 223 The Dialogue: Enter a number: 21 Now enter a letter: A The Result: number = 21 symbol = '\n' '\n' Example The Code: cout > number; cout << "Now enter a letter:\n"; char symbol; cin.get(symbol);

224 Starting Out with C++, 3 rd Edition Slide 6- 224 A Fix To Remove '\n' cout > number; cout >symbol;

225 Starting Out with C++, 3 rd Edition Slide 6- 225 Another '\n' Fix cout > number; new_line( ); // From Display 6.7 cout << "Now enter a letter:\n"; char symbol; cin.get(symbol);

226 Starting Out with C++, 3 rd Edition Slide 6- 226 Detecting the End of a File Member function eof detects the end of a file –Member function of every input-file stream –eof stands for end of file –eof returns a boolean value True when the end of the file has been reached False when there is more data to read –Normally used to determine when we are NOT at the end of the file Example: if ( ! in_stream.eof( ) )

227 Starting Out with C++, 3 rd Edition Slide 6- 227 Using eof This loop reads each character, and writes it to the screen in_stream.get(next); while (! in_stream.eof( ) ) { cout << next; in_stream.get(next); } ( ! In_stream.eof( ) ) becomes false when the program reads past the last character in the file

228 Starting Out with C++, 3 rd Edition Slide 6- 228 The End Of File Character End of a file is indicated by a special character in_stream.eof( ) is still true after the last character of data is read in_stream.eof( ) becomes false when the special end of file character is read

229 Starting Out with C++, 3 rd Edition Slide 6- 229 How To Test End of File We have seen two methods –while ( in_stream >> next) –while ( ! in_stream.eof( ) ) Which should be used? –In general, use eof when input is treated as text and using a member function get to read input –In general, use the extraction operator method when processing numeric data

230 Starting Out with C++, 3 rd Edition The program of Display 6.8… –Reads every character of file cad.dat and copies it to file cplusad.dat except that every 'C' is changed to "C++" in cplusad.dat –Preserves line breaks in cad.dat get is used for input as the extraction operator would skip line breaks get is used to preserve spaces as well – Uses eof to test for end of file Slide 6- 230 Display 6.8 (1) Display 6.8 (2) Program Example: Editing a Text File

231 Starting Out with C++, 3 rd Edition Slide 6- 231 Character Functions Several predefined functions exist to facilitate working with characters The cctype library is required –#include using namespace std;

232 Starting Out with C++, 3 rd Edition Slide 6- 232 The toupper Function toupper returns the argument's upper case character –toupper('a') returns 'A' –toupper('A') return 'A'

233 Starting Out with C++, 3 rd Edition Slide 6- 233 toupper Returns An int Characters are actually stored as an integer assigned to the character toupper and tolower actually return the integer representing the character –cout << toupper('a'); //prints the integer for 'A' –char c = toupper('a'); //places the integer for 'A' in c cout << c; //prints 'A' –cout (toupper('a')); //works too

234 Starting Out with C++, 3 rd Edition isspace returns true if the argument is whitespace –Whitespace is spaces, tabs, and newlines –isspace(' ') returns true –Example: if (isspace(next) ) cout << '-'; else cout << next; –Prints a '-' if next contains a space, tab, or newline character See more character functions in Slide 6- 234 Display 6.9 (1) Display 6.9 (2) The isspace Function

235 Starting Out with C++, 3 rd Edition Slide 6- 235 Section 6.3 Conclusion Can you –Write code that will read a line of text and echo the line with all the uppercase letters deleted? –Describe two methods to detect the end of an input file: –Describe whitespace?

236 Starting Out with C++, 3 rd Edition Slide 6- 236 Chapter 6 -- End

237 Starting Out with C++, 3 rd Edition Display 6.1 Slide 6- 237 Back Next

238 Starting Out with C++, 3 rd Edition Display 6.2 Slide 6- 238 Back Next

239 Starting Out with C++, 3 rd Edition Display 6.3 Slide 6- 239 Back Next

240 Starting Out with C++, 3 rd Edition Display 6.4 (1/2) Slide 6- 240 Back Next

241 Starting Out with C++, 3 rd Edition Display 6.4 (2/2) Slide 6- 241 Back Next

242 Starting Out with C++, 3 rd Edition Display 6.5 Slide 6- 242 Back Next

243 Starting Out with C++, 3 rd Edition Display 6.6 (1/3) Slide 6- 243 Back Next

244 Starting Out with C++, 3 rd Edition Display 6.6 (2/3) Slide 6- 244 Back Next

245 Starting Out with C++, 3 rd Edition Display 6.6 (3/3) Slide 6- 245 Back Next

246 Starting Out with C++, 3 rd Edition Display 6.7 (1/2) Slide 6- 246 Back Next

247 Starting Out with C++, 3 rd Edition Display 6.7 (2/2) Slide 6- 247 Back Next

248 Starting Out with C++, 3 rd Edition Display 6.8 (1/2) Slide 6- 248 Next Back

249 Starting Out with C++, 3 rd Edition Display 6.8 (2/2) Slide 6- 249 Back Next

250 Starting Out with C++, 3 rd Edition Display 6.9 (1/2) Slide 6- 250 Back Next

251 Starting Out with C++, 3 rd Edition Display 6.9 (2/2) Slide 6- 251 Back Next


Download ppt "Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba."

Similar presentations


Ads by Google