Basic file operations in C++ Dr. Ahmed Telba 1. 2 Learning Objectives §C++ I/O streams. §Reading and writing sequential files. §Reading and writing random.

Slides:



Advertisements
Similar presentations
CS 1620 File I/O. So far this semester all input has been from keyboard all output has been to computer screen these are just two examples of where to.
Advertisements

File I/O in C++. Using Input/Output Files A computer file is stored on a secondary storage device (e.g., disk);is stored on a secondary storage device.
1 11/3/08CS150 Introduction to Computer Science 1 Reading from and Writing to Files Section 3.12 & 13.1 & 13.5.
File I/O. COMP104 File I/O / Slide 2 Using Input/Output Files * A computer file n is stored on a secondary storage device (e.g., disk) n is permanent.
計算機概論實習 Files and Streams C++ views file as sequence of bytes Ends with end-of-file marker n-1 end-of-file marker 67 This is.
1 10/29/07CS150 Introduction to Computer Science 1 Reading from and Writing to Files Section 3.12 & 13.1 & 13.5.
17 File Processing. OBJECTIVES In this chapter you will learn:  To create, read, write and update files.  Sequential file processing.  Random-access.
1 10/25/06CS150 Introduction to Computer Science 1 Reading from and Writing to Files.
Tutorial4us.com. File A file is a collection of related data stored in a particular area on the disk. The data is stored in disk using the concept of.
File input and output in C++ Dr. Ahmed Telba. CSE202: Lecture 9The Ohio State University2 Reading & Writing to Files.
Darbas su failais Arnas Terekas IT 1gr. Vilniaus universitetas Matematikos ir informatikos fakultetas.
Dale Roberts 1 Department of Computer and Information Science, School of Science, IUPUI Dale Roberts, Lecturer Computer Science, IUPUI
File I/O ifstreams and ofstreams Sections 11.1 &
Topics 1.File Basics 2.Output Formatting 3.Passing File Stream Objects to Functions 4.More Detailed Error Testing 5.Member Functions for Reading and 6.Writing.
Programming Principles II Lecture Notes 7 Files Andreas Savva.
STL List // constructing lists #include int main () { // constructors used in the same order as described above: std::list first; // empty list of ints.
File handling in C++ BCA Sem III K.I.R.A.S. Using Input/Output Files Files in C++ are interpreted as a sequence of bytes stored on some storage media.
Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba.
Monday, Mar 31, 2003Kate Gregory with material from Deitel and Deitel Week 12 Labs 4 and 5 are back File IO Looking ahead to the final.
File I/O 1 ifstreams and ofstreams Sections 11.1 & 11.2.
“After a day spent staring at a computer monitor, think of a book as a kind of screen saver for your brain” “One good reason why computers can do more.
C++ FILE I/O.
File I/O in C++ II. Open() function Open() is a member function in each classes ( fstream, ifstream, ofstream) Void fstream :: open ( const char *filename,
FILE I/O IN C++. Using Input/Output Files A computer file  is stored on a secondary storage device (e.g., disk);  is permanent;  can be used to provide.
Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba.
Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba.
C++ Programming: chapter 6 – iostream 2014, Spring Pusan National University Ki-Joune Li 1.
File I/O Version 1.0. Topics I/O Streams File I/O Formatting Text Files Handling Stream Errors File Pointers.
Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba.
Mobility Research Lab mobility.ceng.metu.edu.tr Applied Innovative Interdisciplinary (AI2) Research Lab Short Course on Programming in C/C++
Input/Output CSci 588: Data Structures, Algorithms and Software Design Fall 2011 All material not from online sources copyright © Travis Desell, 2011
File Processing Files are used for data persistance-permanent retention of large amounts of data. Computer store files on secondary storage devices,such.
Copyright © 2012 Pearson Addison-Wesley. All rights reserved. Chapter 6 I/O Streams as an Introduction to Objects and Classes.
GE 211 Programming in C ++ Dr. Ahmed Telba Room :Ac -134
C++ Programming: chapter 6 – iostream 2015, Spring Pusan National University Ki-Joune Li 1.
Declaring fstream Objects An istream object named cin connects program and keyboard An ostream object named cout connects the program and the screen These.
Learners Support Publications Working with Files.
Lecture 14 Arguments, Classes and Files. Arguments.
FILE HANDLING(WORKING WITH FILES) FILE- A file is a collection of related data stored in a particular area on the disk. STREAMS- interface between the.
Files To read a file – We must know its name – We must open it (for reading) – Then we can read – Then we must close it That is typically done implicitly.
File I/O in C++. Using Input/Output Files A computer file  is stored on a secondary storage device (e.g., disk);  is permanent;  can be used to provide.
File I/O in C++ I. Using Input/Output Files A computer file is stored on a secondary storage device (e.g., disk); is permanent; can be used to provide.
© Janice Regan, CMPT 128, Jan CMPT 128: Introduction to Computing Science for Engineering Students File Input and Output Checking input for errors.
Computer Programming II Lecture 9. Files Processing - We have been using the iostream standard library, which provides cin and cout methods for reading.
Lecture 2 Fundamental File: Processing Operations
Programming II I/O Streams and Data Files 1(c) Asma AlOsaimi.
CS212: Object Oriented Analysis and Design
What is wrong in the following function definition
File Processing in C++ Data is stored in files so that it may be retrieved for processing when needed.
Basic file operations in C++
Introduction to Programming
Tutorial4us.com File Handling in C++ Tutorial4us.com.
Lecture 9 Files, Pointers
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.
FILE INPUT OUTPUT Skill Area 315 Part B Materials Prepared by
Basic File I/O and Stream Objects
آشنایی با ساختارها و کار با فایلها
files Dr. Bhargavi Goswami Department of Computer Science
Today’s Lecture I/O Streams Tools for File I/O
File Processing in C++ Data is stored in files so that it may be retrieved for processing when needed.
Data File Handling in C++
CPS120: Introduction to Computer Science
CHAPTER 4 File Processing.
C++ Programming: chapter 6 – iostream
Reading from and Writing to Files
File I/O in C++ II.
Lecture 9 Files Handling
Reading from and Writing to Files
Input/Output Streams, Part 2
Text Files.
Presentation transcript:

Basic file operations in C++ Dr. Ahmed Telba 1

2 Learning Objectives §C++ I/O streams. §Reading and writing sequential files. §Reading and writing random access files.

3 Table 12-1

4 Figure 1-1

5 Figure 1-2

6 C++ Files and Streams §Why use File Handling §For permanent storage. §The transfer of input - data or output - data from one computer to another can be easily done by using files. §For read and write from a file you need another standard C++ library called fstream, which defines three new data types:

7 DatatypeDescription ofstreamThis is used to create a file and write data on files ifstreamThis is used to read data from files fstreamThis is used to both read and write data from/to files

How to achieve File Handling  For achieving file handling in C++ we need follow following steps Naming a file Opening a file Reading data from file Writing data into file Closing a file 8

Functions use in File Handling FunctionOperation open()To create a file close()To close an existing file get()Read a single character from a file put()write a single character in file. read()Read data from file write()Write data into file. 9

10 Closing a File A file must be close after completion of all operation related to file. For closing file we need close() function. Syntax outfile.close(); Defining and Opening a File The function open() can be used to open multiple files that use the same stream object. Syntax file-stream-class stream-object; stream-object.open("filename"); Example ofstream outfile; // create stream outfile. open ("data1"); // connect stream to data1

File Opening mode ModeMeaningPurpose ios :: outWriteOpen the file for write only. ios :: inreadOpen the file for read only. ios :: appAppendingOpen the file for appending data to end-of-file. ios :: ateAppendingtake us to the end of the file when it is opened. 11 Example fstream file; file.Open("data. txt", ios :: out | ios :: in);

FLAGES IN FILE §FLAGES IN FILE 12

13 File Open Modes ios:: app - (append) write all output to the end of file ios:: ate - data can be written anywhere in the file ios:: binary - read/write data in binary format ios:: in - (input) open a file for input ios::out - (output) open afile for output ios: trunc -(truncate) discard the files’ contents if it exists

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.

File Names §All files are assigned a name that is used for identification purposes by the operating system and the user.

16 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 § # include

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. 17

18 Path of 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 ");

§// 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; §} 19

Writing to 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"; §return 0; §} 20

§#include §using namespace std; §int main() § { §ofstream fout; § fout.open("FF.txt"); § fout << "HELLOW FILE.\n"<< "WELCOME YOU PROGRAM\n" §<< "WHAT DA YOU LIKE OF ME\n"; § fout.close(); §} 21

§// writing in file §#include //divide by 7 §#include §using namespace std; § int main() §{ §ofstream fout("data.txt"); §for(int i=4;i<=200;i++) §{ §if(i%7==0) §fout<<i<<" : divide by Two (7)."<<"\n"; §} §fout.close(); §} 22

§#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; § } 23

24 Testing for Open Errors dataFile.open(“cust.txt”, ios::in); if (!dataFile) { cout << “Error opening file.\n”; }

25 Another way to Test for Open Errors dataFile.open(“cust.dat”, ios::in); if (dataFile.fail()) { cout << “Error opening file.\n”; }

// writing on a text file §// writing on a text file §#include §using namespace std; §int main () { § ofstream myfile ("examplett.dat"); § 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"; §return 0; §} 26

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(); §return 0; } 27

§#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:..txt "; § cin >> FileName; § ofstream Students(FileName, ios::out); § Students << FirstName << "\n" << LastName << "\n" << Age; § cout << "\n\n"; § return 0; §} 28

Write to file §#include §using namespace std; §int main() § { ofstream fout; § fout.open("FFFF.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(); §} 29

§//Write the odd number in file §#include §using namespace std; §int main() § { ofstream fout; § fout.open("E:\\firsteee.txt"); §int i,j; §for(i=2;i<30;i+=2) §{ §fout<<i<<"\t"; §cout<<i<<"\t";} § fout.close(); §} 30

§// print in file Even number 1:30 §#include §using namespace std; §int main() § { ofstream fout; § fout.open("D:\\firstExa.txt"); §int i,j; §for(i=1;i<30;i+=2) §fout<<i<<"\t"; § fout.close(); §} 31

§#include §using namespace std; §int 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(); § } 32

§//write equation for this series §#include §using namespace std; § int 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; §} 33

§#include // using both file and screen §#include §using namespace std; § int main() §{ § ofstream fout; § fout.open("xxxx.txt"); § int i,j,m,n,sum; §sum=0; §cout<<"equation for this series ="<<endl; §cin>>n; §for(i=1 ;i<=n ;i++) §{ §m=i*i; §sum=sum+m; } §cout<< "seque="<<sum<< endl; §fout<< "seque= written in file is="<<sum<< endl; §fout.close(); §} 34

§#include §using namespace std; § int 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; §} 35

§#include §using namespace std; §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(); §} 36

§//Fenonci seris §#include §using namespace std; §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(); § } 37

§//write to file §#include §using namespace std; § int 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(); §} 38

Read from file §#include §using namespace std; § int main() § { char array [80]; § ifstream fin; § fin.open("firstExa.txt"); § while(!fin.eof()) § {fin.getline(array,80); § cout<<array<<endl;} § fin.close(); §} 39

Write in binary file § ofstream fout ; § fout.open("file path",iostream family § fout.write((char*)& data,sizeo(data); 40

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"); § } 41

§// 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; §} Slide 6- 42

§// 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"; §return 0; §} Slide 6- 43

Using fout Slide §#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; §return 0;}

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(); §return 0; §} 45

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(); §return 0; §} 46

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; §} 47

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. 48

Reading from file §#include §using namespace std; §int main() §{ §char m; §int i; §double j; §ifstream fin("data.txt"); §fin >> m >> i >> j; §cout << m << endl §<< i << endl §<< j << endl ; §fin.close();} 49

§// 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; §} 50

classdefault mode parameter ofstreamios::out ifstreamios::in fstreamios::in | ios::out ofstream myfile; myfile.open ("example.bin", ios::out | ios::app | ios::binary); 51

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; §} 52

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; §} 53

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. 54

§// reading a text file §#include §using namespace std; §int main () { §char buffer[256]; §ifstream examplefile ("examplepp.txt"); §if (! examplefile.is_open()) §{ cout << "Error opening file"; exit (1); } §while (! examplefile.eof() ) §{ §examplefile.getline (buffer,100); §cout << buffer << endl; §} §return 0; §} 55

§// 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; §} 56