Chapter 8 File Processing
|
|
- Cornelius Peters
- 6 years ago
- Views:
Transcription
1 Chapter 8 File Processing Outline 1 Introduction 2 The Data Hierarchy 3 Files and Streams 4 Creating a Sequential Access File 5 Reading Data from a Sequential Access File 6 Updating Sequential Access Files 7 Random Access Files 8 Creating a Random Access File 9 Writing Data Randomly to a Random Access File 10 Reading Data Sequentially from a Random Access File 11 Case Study: A Transaction Processing Program 12 Input/Output of Objects 1
2 Introduction Storage of data Arrays, variables are temporary Files are permanent Magnetic disk, optical disk, tapes Create, update, process files by programs C/C++ or other Sequential and random access Formatted and raw processing 2
3 The Data Hierarchy Data Hierarchy: Bit smallest data item Value of 0 or 1 Byte 8 bits Used to store a character (char) Decimal digits, letters, and special symbols Also Unicode for large character sets (wchar_t) 3
4 The Data Hierarchy From smallest to largest (continued) Field: group of characters with some meaning Your name Record: group of related fields struct or class in C++ In payroll system, could be name, SS#, address, wage Each field associated with same employee Record key: field used to uniquely identify record File: group of related records Payroll for entire company Sequential file: records stored by key Database: group of related files Payroll, accounts-receivable, inventory 4
5 The Data Hierarchy Data Hierarchy (continued): File group of related records Example: payroll file Database group of related files Sally Black Tom Blue Judy Green Iris Orange Randy Red File Judy Green Record Judy Field Byte (ASCII character J) 1 Bit 5
6 The Data Hierarchy Data files Record key Identifies a record to facilitate the retrieval of specific records from a file Sequential file Records typically sorted by key 6
7 Files and Streams C/C++ view file as sequence of bytes Ends with end-of-file marker n-1... end-of-file marker When file opened (C++) Object created, stream associated with it cin, cout, etc. created when <iostream> included Communication between program and file/device 7
8 Files and Streams When file opened (C) Returns pointer to a FILE structure Example file pointers: stdin - standard input (keyboard) stdout - standard output (screen) stderr - standard error (screen) FILE structure File descriptor Index into operating system array called the open file table File Control Block (FCB) Found in every array element, system uses it to administer the file 8
9 Files and Streams (C++) To perform file processing Include <iostream> and <fstream> Class templates basic_ifstream (input) basic_ofstream (output) basic_fstream (I/O) typedefs for specializations that allow char I/O ifstream (char input) ofstream (char output) fstream (char I/O) 9
10 Opening files Files and Streams (C++) Create objects from template Derive from stream classes Can use stream methods put, get, peek, etc. basic_ios basic_istream basic_ostream basic_ifstream basic_iostream basic_ofstream basic_fstream 10
11 Files and Streams (C) Read/Write functions in standard C library fgetc Reads one character from a file Takes a FILE pointer as an argument fgetc( stdin) equivalent to getchar() fputc Writes one character to a file Takes a FILE pointer and a character to write as an argument fputc('a', stdout) equivalent to putchar('a') fgets Reads a line from a file fputs Writes a line to a file fscanf / fprintf File processing equivalents of scanf and printf 11
12 Creating a Sequential-Access File (C++) C++ imposes no structure on file Concept of "record" must be implemented by programmer To open file, create objects Creates "line of communication" from object to file Classes ifstream (input only) ofstream (output only) fstream (I/O) Simplest ofstream outclientfile( filename"); ifstream inclientfile( filename"); Can use with file-open mode ofstream outclientfile( filename", fileopenmode ); ifstream inclientfile( filename", fileopenmode ); Several other ways 12
13 Creating a Sequential-Access File (C++) File-open modes Mode Description ios::app ios::ate ios::in ios::out ios::trunc ios::binary Write all output to the end of the file. Open a file for output and move to the end of the file (normally used to append data to a file). Data can be written anywhere in the file. Open a file for input. Open a file for output. Discard the file s contents if it exists (this is also the default action for ios::out) Open a file for binary (i.e., non-text) input or output. ofstream opened for output by default ofstream outclientfile( "clients.dat", ios::out ); ofstream outclientfile( "clients.dat"); 13
14 Creating a Sequential-Access File (C++) Operations Writing to file (just like cout) outclientfile << myvariable Closing file outclientfile.close() Automatically closed when destructor called 14
15 Creating a Sequential Access File (in C) C (like C++) imposes no file structure No notion of records in a file Programmer must provide file structure Creating a File FILE *myptr; Creates a FILE pointer called myptr myptr = fopen("myfile.dat", openmode); Function fopen returns a FILE pointer to file specified Takes two arguments file to open and file open mode If open fails, NULL returned fprintf Used to print to a file Like printf, except first argument is a FILE pointer (pointer to the file you want to print in) 15
16 Creating a Sequential Access File (in C) feof(file pointer) Returns true if end-of-file indicator (no more data to process) is set for the specified file fclose(file pointer) Closes specified file Performed automatically when program ends Good practice to close files explicitly Details Programs may process no files, one file, or many files Each file must have a unique name and should have its own pointer 16
17 Creating a Sequential Access File (in C) Table of file open modes: Mode Description r w a Open a file for reading. Create a file for writing. If the file already exists, discard the current contents. Append; open or create a file for writing at end of file. r+ Open a file for update (reading and writing). w+ Create a file for update. If the file already exists, discard the current contents. a+ Append; open or create a file for update; writing is done at the end of the file. 17
18 1 // Fig. 14.4: fig14_04.cpp 2 // Create a sequential file in C++ 3 #include <iostream> 4 5 using std::cout; 6 using std::cin; 7 using std::ios; 8 using std::cerr; 9 using std::endl; #include <fstream> Notice the header files 12 required for file I/O. 13 using std::ofstream; #include <cstdlib> // exit prototype int main() 18 { 19 // ofstream opens file 20 ofstream outclientfile( "clients.dat", ios::out ); // exit program if unable to create file 23 if (!outclientfile ) { 24 cerr << "File could not be opened" << endl; 25 exit( 1 ); } // end if ofstream object created and used to open file "clients.dat". If the file does not exist, it is created.! operator used to test if the file opened properly.
19 28 29 cout << "Enter the account, name, and balance." << endl 30 << "Enter end-of-file to end input.\n? "; int account; 33 char name[ 30 ]; 34 double balance; // read account, name and balance from cin, then place in file 37 while ( cin >> account >> name >> balance ) { 38 outclientfile << account << ' ' << name << ' ' << balance 39 << endl; 40 cout << "? "; } // end while return 0; // ofstream destructor closes file } // end main cin is implicitly converted to a pointer. When EOF is encountered, it returns 0 and the loop stops. Write data to file like a regular stream. File closed when destructor called for object. Can be explicitly closed with close().
20 /* Create a sequential file in C */ #include <stdio.h> int main() { int account; char name[ 30 ]; double balance; /* 1. Initialize variables and FILE pointer */ FILE *cfptr; /* cfptr = clients.dat file pointer */ /* 1.1 Link the pointer to a file */ if ( ( cfptr = fopen( "clients.dat", "w" ) ) == NULL ) printf( "File could not be opened\n" ); else { /* 2. Input data */ printf( "Enter the account, name, and balance.\n" ); printf( "Enter EOF to end input.\n" ); printf( "? " ); scanf( "%d%s%lf", &account, name, &balance );
21 /* 2.1 Write to file (fprintf) */ while (!feof( stdin ) ) { fprintf( cfptr, "%d %s %.2f\n", account, name, balance ); printf( "? " ); scanf( "%d%s%lf", &account, name, &balance ); } /* 3. Close file */ } fclose( cfptr ); } return 0; 21
22 Program Output Enter the account, name, and balance. Enter EOF to end input.? 100 Jones 24.98? 200 Doe ? 300 White 0.00? 400 Stone ? 500 Rich ? 22
23 Reading Data from a Sequential-Access File (C++) Reading files ifstream inclientfile( "filename", ios::in );!inclientfile tests if file was opened properly Stops when EOF found while (!inclientfile.eof()) or while ( inclientfile >> account >> name >> balance ) 23
24 1 // Fig. 14.7: fig14_07.cpp 2 // Reading and printing a sequential file in C++. 3 #include <iostream> 4 5 using std::cout; 6 using std::cin; 7 using std::ios; 8 using std::cerr; 9 using std::endl; 10 using std::left; fig14_07.cpp (1 of 3) 11 using std::right; 12 using std::fixed; 13 using std::showpoint; #include <fstream> using std::ifstream; #include <iomanip> using std::setw; 22 using std::setprecision; #include <cstdlib> // exit prototype void outputline( int, const char * const, double );
25 28 int main() 29 { 30 // ifstream constructor opens the file 31 ifstream inclientfile( "clients.dat", ios::in ); // exit program if ifstream could not open file 34 if (!inclientfile ) { 35 cerr << "File could not be opened" << endl; 36 exit( 1 ); 37 fig14_07.cpp (2 of 3) 38 } // end if int account; 41 char name[ 30 ]; 42 double balance; cout << left << setw( 10 ) << "Account" << setw( 13 ) 45 << "Name" << "Balance" << endl << Read fixed from << showpoint; file until EOF 46 found. 47 // display each record in file 48 while ( inclientfile >> account >> name >> balance ) 49 outputline( account, name, balance ); return 0; // ifstream destructor closes the file } // end main Open and test file for input.
26 54 55 // display single record from file 56 void outputline( int account, const char * const name, 57 double balance ) 58 { 59 cout << left << setw( 10 ) << account << setw( 13 ) << name 60 << setw( 7 ) << setprecision( 2 ) << right << balance fig14_07.cpp (3 of 3) 61 << endl; 62 fig14_07.cpp output (1 of 1) 63 } // end function outputline Account Name 100 Jones Doe White Stone Rich Balance
27 Reading Data from a Sequential-Access File (C++) File position pointers Number of next byte to read/write Functions to reposition pointer seekg (seek get for istream class) seekp (seek put for ostream class) Classes have "get" and "put" pointers seekg and seekp take offset and direction Offset: number of bytes relative to direction Direction (ios::beg default) ios::beg - relative to beginning of stream ios::cur - relative to current position ios::end - relative to end 27
28 Reading Data from a Sequential-Access File (C++) Examples fileobject.seekg(0) Goes to front of file (location 0) because ios::beg is default fileobject.seekg(n) Goes to nth byte from beginning fileobject.seekg(n, ios::cur) Goes n bytes forward fileobject.seekg(y, ios::end) Goes y bytes back from end fileobject.seekg(0, ios::cur) Goes to last byte seekp similar 28
29 Reading Data from a Sequential-Access File (C++) To find pointer location tellg and tellp location = fileobject.tellg() Upcoming example Credit manager program List accounts with zero balance, credit, and debit 29
30 1 // Fig. 14.8: fig14_08.cpp 2 // Credit-inquiry program. 3 #include <iostream> 4 5 using std::cout; 6 using std::cin; 7 using std::ios; 8 using std::cerr; 9 using std::endl; 10 using std::fixed; 11 using std::showpoint; 12 using std::left; 13 using std::right; #include <fstream> using std::ifstream; #include <iomanip> using std::setw; 22 using std::setprecision; #include <cstdlib> 25
31 26 enum RequestType { ZERO_BALANCE = 1, CREDIT_BALANCE, 27 DEBIT_BALANCE, END }; 28 int getrequest(); 29 bool shoulddisplay( int, double ); 30 void outputline( int, const char * const, double ); int main() 33 { 34 // ifstream constructor opens the file 35 ifstream inclientfile( "clients.dat", ios::in ); fig14_08.cpp (2 of 6) // exit program if ifstream could not open file 38 if (!inclientfile ) { 39 cerr << "File could not be opened" << endl; 40 exit( 1 ); } // end if int request; 45 int account; 46 char name[ 30 ]; 47 double balance; // get user's request (e.g., zero, credit or debit balance) 50 request = getrequest(); 51
32 52 // process user's request 53 while ( request!= END ) { switch ( request ) { case ZERO_BALANCE: 58 cout << "\naccounts with zero balances:\n"; 59 break; 60 fig14_08.cpp (3 of 6) 61 case CREDIT_BALANCE: 62 cout << "\naccounts with credit balances:\n"; 63 break; case DEBIT_BALANCE: 66 cout << "\naccounts with debit balances:\n"; 67 break; } // end switch 70
33 71 // read account, name and balance from file 72 inclientfile >> account >> name >> balance; // display file contents (until eof) 75 while (!inclientfile.eof() ) { // display record 78 if ( shoulddisplay( request, balance ) ) 79 outputline( account, name, balance ); // read account, name and balance from file 82 inclientfile >> account >> name >> balance; 83 Use clear to reset eof. Use 84 } // end inner while seekg to set file position 85 pointer to beginning of file. 86 inclientfile.clear(); // reset eof for next input 87 inclientfile.seekg( 0 ); // move to beginning of file 88 request = getrequest(); // get additional request from user } // end outer while cout << "End of run." << endl; return 0; // ifstream destructor closes the file } // end main
34 97 98 // obtain request from user 99 int getrequest() 100 { 101 int request; // display request options 104 cout << "\nenter request" << endl 105 << " 1 - List accounts with zero balances" << endl 106 << " 2 - List accounts with credit balances" << endl 107 << " 3 - List accounts with debit balances" << endl 108 << " 4 - End of run" << fixed << showpoint; // input user request 111 do { 112 cout << "\n? "; 113 cin >> request; } while ( request < ZERO_BALANCE && request > END ); return request; } // end function getrequest 120
35 121 // determine whether to display given record 122 bool shoulddisplay( int type, double balance ) 123 { 124 // determine whether to display credit balances 125 if ( type == CREDIT_BALANCE && balance < 0 ) 126 return true; // determine whether to display debit balances 129 if ( type == DEBIT_BALANCE && balance > 0 ) 130 return true; fig14_08.cpp (6 of 6) // determine whether to display zero balances 133 if ( type == ZERO_BALANCE && balance == 0 ) 134 return true; return false; } // end function shoulddisplay // display single record from file 141 void outputline( int account, const char * const name, 142 double balance ) 143 { 144 cout << left << setw( 10 ) << account << setw( 13 ) << name 145 << setw( 7 ) << setprecision( 2 ) << right << balance 146 << endl; 147
36 Enter request 1 - List accounts with zero balances 2 - List accounts with credit balances 3 - List accounts with debit balances 4 - End of run? 1 Accounts with zero balances: fig14_08.cpp output (1 of 2) 300 White 0.00 Enter request 1 - List accounts with zero balances 2 - List accounts with credit balances 3 - List accounts with debit balances 4 - End of run? 2 Accounts with credit balances: 400 Stone
37 Enter request 1 - List accounts with zero balances 2 - List accounts with credit balances 3 - List accounts with debit balances 4 - End of run? 3 Accounts with debit balances: 100 Jones Doe Rich Enter request 1 - List accounts with zero balances 2 - List accounts with credit balances 3 - List accounts with debit balances 4 - End of run? 4 End of run.
38 Reading Data from a Sequential Access File (in C) Reading a sequential access file Create a FILE pointer, link it to the file to read myptr = fopen( "myfile.dat", "r" ); Use fscanf to read from the file Like scanf, except first argument is a FILE pointer fscanf( myptr, "%d%s%f", &myint, &mystring, &myfloat ); Data read from beginning to end File position pointer Indicates number of next byte to be read / written Not really a pointer, but an integer value (specifies byte location) Also called byte offset rewind( myptr ) Repositions file position pointer to beginning of file (byte 0) 38
39 1 /* 2 Reading and printing a sequential file in C */ 3 #include <stdio.h> 4 5 int main() 6 { 7 int account; 8 char name[ 30 ]; 9 double balance; 10 FILE *cfptr; /* cfptr = clients.dat file pointer */ if ( ( cfptr = fopen( "clients.dat", "r" ) ) == NULL ) 13 printf( "File could not be opened\n" ); 14 else { 15 printf( "%-10s%-13s%s\n", "Account", "Name", "Balance" ); 16 fscanf( cfptr, "%d%s%lf", &account, name, &balance ); while (!feof( cfptr ) ) { 19 printf( "%-10d%-13s%7.2f\n", account, name, balance ); 20 fscanf( cfptr, "%d%s%lf", &account, name, &balance ); 21 } fclose( cfptr ); 24 } return 0; 27}
40 Program Output Account Name Balance 100 Jones Doe White Stone Rich
41 /* Credit inquiry program in C */ #include <stdio.h> int main() { int request, account; double balance; char name[ 30 ]; FILE *cfptr; if ( ( cfptr = fopen( "clients.dat", "r" ) ) == NULL ) printf( "File could not be opened\n" ); else { printf( "Enter request\n" " 1 - List accounts with zero balances\n" " 2 - List accounts with credit balances\n" " 3 - List accounts with debit balances\n" " 4 - End of run\n? " ); scanf( "%d", &request ); while ( request!= 4 ) { fscanf( cfptr, "%d%s%lf", &account, name, &balance );
42 switch ( request ) { case 1: printf( "\naccounts with zero " "balances:\n" ); while (!feof( cfptr ) ) { if ( balance == 0 ) printf( "%-10d%-13s%7.2f\n", account, name, balance ); } fscanf( cfptr, "%d%s%lf", &account, name, &balance ); break; 42
43 case 2: printf( "\naccounts with credit " "balances:\n" ); while (!feof( cfptr ) ) { if ( balance < 0 ) printf( "%-10d%-13s%7.2f\n", account, name, balance ); } fscanf( cfptr, "%d%s%lf", &account, name, &balance ); break; 43
44 case 3: printf( "\naccounts with debit " "balances:\n" ); while (!feof( cfptr ) ) { if ( balance > 0 ) printf( "%-10d%-13s%7.2f\n", account, name, balance ); } fscanf( cfptr, "%d%s%lf", &account, name, &balance ); } break; 44
45 } rewind( cfptr ); printf( "\n? " ); scanf( "%d", &request ); } printf( "End of run.\n" ); fclose( cfptr ); } return 0;
46 Enter request 1 - List accounts with zero balances 2 - List accounts with credit balances 3 - List accounts with debit balances 4 - End of run? 1 Program Output Accounts with zero balances: 300 White 0.00? 2 Accounts with credit balances: 400 Stone ? 3 Accounts with debit balances: 100 Jones Doe Rich ? 4 End of run.
47 Updating Sequential Access File: Problem Sequential access file Cannot be modified without the risk of destroying other data Fields can vary in size Formatted text different from internal representation Different representation in files and screen than internal representation 1, 34, -890 are allints, but have different sizes on disk 47
48 Updating Sequential Access File: Problem Updating sequential files Risk overwriting other data Problem can be avoided, but awkward 300 White Jones (old data in file) If we want to change White's name to Worthington, 300 Worthington White Jones Data gets overwritten 300 Worthington 0.00ones
Fundamentals of Programming Session 27
Fundamentals of Programming Session 27 Instructor: Reza Entezari-Maleki Email: entezari@ce.sharif.edu 1 Fall 2013 These slides have been created using Deitel s slides Sharif University of Technology Outlines
More informationIS 0020 Program Design and Software Tools
1 IS 0020 Program Design and Software Tools Stack/Queue - File Processing Lecture 10 March 29, 2005 Introduction 2 Storage of data Arrays, variables are temporary Files are permanent Magnetic disk, optical
More informationLecture 9. Introduction
Lecture 9 File Processing Streams Stream I/O template hierarchy Create, update, process files Sequential and random access Formatted and raw processing Namespaces Lec 9 Programming in C++ 1 Storage of
More informationFundamentals of Programming Session 28
Fundamentals of Programming Session 28 Instructor: Reza Entezari-Maleki Email: entezari@ce.sharif.edu 1 Fall 2014 These slides have been created using Deitel s slides Sharif University of Technology Outlines
More informationFundamentals of Programming Session 25
Fundamentals of Programming Session 25 Instructor: Reza Entezari-Maleki Email: entezari@ce.sharif.edu 1 Fall 2013 These slides have been created using Deitel s slides Sharif University of Technology Outlines
More informationLecture6 File Processing
1 Lecture6 File Processing Dr. Serdar ÇELEBİ 2 Introduction The Data Hierarchy Files and Streams Creating a Sequential Access File Reading Data from a Sequential Access File Updating Sequential Access
More informationCh 11. C File Processing (review)
Ch 11 C File Processing (review) OBJECTIVES To create, read, write and update files. Sequential access file processing. Data Hierarchy Data Hierarchy: Bit smallest data item Value of 0 or 1 Byte 8 bits
More informationChapter 11 File Processing
1 Chapter 11 File Processing Copyright 2007 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 2 Chapter 11 File Processing Outline 11.1 Introduction 11.2 The Data Hierarchy 11.3
More informationC++ Programming Lecture 10 File Processing
C++ Programming Lecture 10 File Processing By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department Outline Introduction. The Data Hierarchy. Files and Streams. Creating a Sequential
More informationENG120. Misc. Topics
ENG120 Misc. Topics Topics Files in C Using Command-Line Arguments Typecasting Working with Multiple source files Conditional Operator 2 Files and Streams C views each file as a sequence of bytes File
More informationLecture 8. Dr M Kasim A Jalil. Faculty of Mechanical Engineering UTM (source: Deitel Associates & Pearson)
Lecture 8 Data Files Dr M Kasim A Jalil Faculty of Mechanical Engineering UTM (source: Deitel Associates & Pearson) Objectives In this chapter, you will learn: To be able to create, read, write and update
More informationChapter 12. Files (reference: Deitel s chap 11) chap8
Chapter 12 Files (reference: Deitel s chap 11) 20061025 chap8 Introduction of File Data files Can be created, updated, and processed by C programs Are used for permanent storage of large amounts of data
More informationC File Processing: One-Page Summary
Chapter 11 C File Processing C File Processing: One-Page Summary #include int main() { int a; FILE *fpin, *fpout; if ( ( fpin = fopen( "input.txt", "r" ) ) == NULL ) printf( "File could not be
More informationby Pearson Education, Inc. All Rights Reserved. 2
In Fig. 17.4, the file is to be opened for output, so an ofstream object is created. Two arguments are passed to the object s constructor the filename and the file-open mode (line 12). For an ofstream
More informationChapter 14 File Processing
Chapter 14 File Processing Outline 14.1 Introd uction 14.2 The Data Hie rarchy 14.3 File s and Stre am s 14.4 Cre ating a Se q ue ntialacce ss File 14.5 Re ad ing Data from a Se q ue ntialacce ss File
More informationC: How to Program. Week /June/18
C: How to Program Week 17 2007/June/18 1 Chapter 11 File Processing Outline 11.1 Introduction 11.2 The Data Hierarchy 11.3 Files and Streams 11.4 Creating a Sequential Access File 11.5 Reading Data from
More informationC How to Program, 6/e by Pearson Education, Inc. All Rights Reserved.
C How to Program, 6/e Storage of data in variables and arrays is temporary such data is lost when a program terminates. Files are used for permanent retention of data. Computers store files on secondary
More informationFile Processing. Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan
File Processing Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan Outline 11.2 The Data Hierarchy 11.3 Files and Streams 11.4 Creating a Sequential
More informationIS 0020 Program Design and Software Tools
1 IS 0020 Program Design and Software Tools Exception Handling, File Processing Lecture 11 March 30, 2004 Introduction 2 Exceptions Indicates problem occurred in program Not common An "exception" to a
More informationFundamentals of Programming. Lecture 15: C File Processing
1 Fundamentals of Programming Lecture 15: C File Processing Instructor: Fatemeh Zamani f_zamani@ce.sharif.edu Sharif University of Technology Computer Engineering Department The lectures of this course
More informationThis chapter introduces the notion of namespace. We also describe how to manage input and output with C++ commands via the terminal or files.
C++ PROGRAMMING LANGUAGE: NAMESPACE AND MANGEMENT OF INPUT/OUTPUT WITH C++. CAAM 519, CHAPTER 15 This chapter introduces the notion of namespace. We also describe how to manage input and output with C++
More informationby Pearson Education, Inc. All Rights Reserved. 2
The C++ standard libraries provide an extensive set of input/output capabilities. C++ uses type-safe I/O. Each I/O operation is executed in a manner sensitive to the data type. If an I/O member function
More informationSTRUCTURES & FILE IO
STRUCTURES & FILE IO Structures Collections of related variables (aggregates) under one name Can contain variables of different data types Commonly used to define records to be stored in files Combined
More informationLecture 9: File Processing. Quazi Rahman
60-141 Lecture 9: File Processing Quazi Rahman 1 Outlines Files Data Hierarchy File Operations Types of File Accessing Files 2 FILES Storage of data in variables, arrays or in any other data structures,
More informationPhysical Files and Logical Files. Opening Files. Chap 2. Fundamental File Processing Operations. File Structures. Physical file.
File Structures Physical Files and Logical Files Chap 2. Fundamental File Processing Operations Things you have to learn Physical files and logical files File processing operations: create, open, close,
More informationC++ files and streams. Lec 28-31
C++ files and streams Lec 28-31 Introduction So far, we have been using the iostream standard library, which provides cin and cout methods for reading from standard input and writing to standard output
More informationConvenient way to deal large quantities of data. Store data permanently (until file is deleted).
FILE HANDLING Why to use Files: Convenient way to deal large quantities of data. Store data permanently (until file is deleted). Avoid typing data into program multiple times. Share data between programs.
More informationChapter-12 DATA FILE HANDLING
Chapter-12 DATA FILE HANDLING Introduction: A file is a collection of related data stored in a particular area on the disk. Programs can be designed to perform the read and write operations on these files.
More informationC++ Binary File I/O. C++ file input and output are typically achieved by using an object of one of the following classes:
C++ Binary File I/O C++ file input and output are typically achieved by using an object of one of the following classes: ifstream for reading input only. ofstream for writing output only. fstream for reading
More informationUnit-V File operations
Unit-V File operations What is stream? C++ IO are based on streams, which are sequence of bytes flowing in and out of the programs. A C++ stream is a flow of data into or out of a program, such as the
More informationObject Oriented Programming In C++
C++ Question Bank Page 1 Object Oriented Programming In C++ 1741059 to 1741065 Group F Date: 31 August, 2018 CIA 3 1. Briefly describe the various forms of get() function supported by the input stream.
More informationIS 0020 Program Design and Software Tools
1 Introduction 2 IS 0020 Program Design and Software Tools File Processing, Standard Template Library Lecture 10 Storage of data Arrays, variables are temporary Files are permanent Magnetic disk, optical
More informationUNIT V FILE HANDLING
UNIT V CONTENTS: Streams and formatted I/O I/O manipulators File handling Random access Object serialization Namespaces Std namespace ANSI String Objects Standard template library FILE HANDLING Streams:
More informationAfter going through this lesson, you would be able to: store data in a file. access data record by record from the file. move pointer within the file
16 Files 16.1 Introduction At times it is required to store data on hard disk or floppy disk in some application program. The data is stored in these devices using the concept of file. 16.2 Objectives
More informationStandard File Pointers
1 Programming in C Standard File Pointers Assigned to console unless redirected Standard input = stdin Used by scan function Can be redirected: cmd < input-file Standard output = stdout Used by printf
More informationChapter 12 - C++ Stream Input/Output
Chapter 12 - C++ Stream Input/Output 1 12.1 Introduction 12.2 Streams 12.2.1 Classic Streams vs. Standard Streams 12.2.2 iostream Library Header Files 12.2.3 Stream Input/Output Classes and Objects 12.3
More informationStreams contd. Text: Chapter12, Big C++
Streams contd pm_jat@daiict.ac.in Text: Chapter12, Big C++ Streams Objects are Abstracted Wrapper around input/output source/destinations Steps in reading/writing streams- Open: Establish connection between
More informationFall 2017 CISC/CMPE320 9/27/2017
Notices: CISC/CMPE320 Today File I/O Text, Random and Binary. Assignment 1 due next Friday at 7pm. The rest of the assignments will also be moved ahead a week. Teamwork: Let me know who the team leader
More informationAdvanced I/O Concepts
Advanced Object Oriented Programming Advanced I/O Concepts Seokhee Jeon Department of Computer Engineering Kyung Hee University jeon@khu.ac.kr 1 1 Streams Diversity of input sources or output destinations
More informationFile I/O. Arash Rafiey. November 7, 2017
November 7, 2017 Files File is a place on disk where a group of related data is stored. Files File is a place on disk where a group of related data is stored. C provides various functions to handle files
More informationRandom File Access. 1. Random File Access
Random File Access 1. Random File Access In sequential file access, the file is read or written sequentially from the beginning. In random file access, you can skip around to various points in the file
More informationCSc Introduc/on to Compu/ng. Lecture 19 Edgardo Molina Fall 2011 City College of New York
CSc 10200 Introduc/on to Compu/ng Lecture 19 Edgardo Molina Fall 2011 City College of New York 18 Standard Device Files Logical file object: Stream that connects a file of logically related data to a program
More informationMode Meaning r Opens the file for reading. If the file doesn't exist, fopen() returns NULL.
Files Files enable permanent storage of information C performs all input and output, including disk files, by means of streams Stream oriented data files are divided into two categories Formatted data
More informationC for Engineers and Scientists: An Interpretive Approach. Chapter 14: File Processing
Chapter 14: File Processing Files and Streams C views each file simply as a sequential stream of bytes. It ends as if there is an end-of-file marker. The data structure FILE, defined in stdio.h, stores
More informationDeveloped By : Ms. K. M. Sanghavi
Developed By : Ms. K. M. Sanghavi Designing Our Own Manipulators We can design our own manipulators for certain special purpose.the general form for creating a manipulator without any arguments is: ostream
More informationAccessing Files in C. Professor Hugh C. Lauer CS-2303, System Programming Concepts
Accessing Files in C Professor Hugh C. Lauer CS-2303, System Programming Concepts (Slides include materials from The C Programming Language, 2 nd edition, by Kernighan and Ritchie, Absolute C++, by Walter
More informationA stream is infinite. File access methods. File I/O in C++ 4. File input/output David Keil CS II 2/03. The extractor and inserter form expressions
Topic: File input/output I. Streams II. Access methods III. C++ style Input, output, random access Stream classes: ifstream, ofstream IV. C style The FILE data type Opening files Writing to, reading text
More informationComputer programming
Computer programming "He who loves practice without theory is like the sailor who boards ship without a ruder and compass and never knows where he may cast." Leonardo da Vinci T.U. Cluj-Napoca - Computer
More informationby Pearson Education, Inc. All Rights Reserved. 2
Data that is formatted and written to a sequential file as shown in Section 17.4 cannot be modified without the risk of destroying other data in the file. For example, if the name White needs to be changed
More informationChapter 15 - C++ As A "Better C"
Chapter 15 - C++ As A "Better C" Outline 15.1 Introduction 15.2 C++ 15.3 A Simple Program: Adding Two Integers 15.4 C++ Standard Library 15.5 Header Files 15.6 Inline Functions 15.7 References and Reference
More informationCS2141 Software Development using C/C++ Stream I/O
CS2141 Software Development using C/C++ Stream I/O iostream Two libraries can be used for input and output: stdio and iostream The iostream library is newer and better: It is object oriented It can make
More informationInput / Output Functions
CSE 2421: Systems I Low-Level Programming and Computer Organization Input / Output Functions Presentation G Read/Study: Reek Chapter 15 Gojko Babić 10-03-2018 Input and Output Functions The stdio.h contain
More informationFile IO and command line input CSE 2451
File IO and command line input CSE 2451 File functions Open/Close files fopen() open a stream for a file fclose() closes a stream One character at a time: fgetc() similar to getchar() fputc() similar to
More informationChapter 14 Sequential Access Files
Chapter 14 Sequential Access Files Objectives Create file objects Open a sequential access file Determine whether a sequential access file was opened successfully Write data to a sequential access file
More informationLecture 5 Files and Streams
Lecture 5 Files and Streams Introduction C programs can store results & information permanently on disk using file handling functions These functions let you write either text or binary data to a file,
More informationCMPE-013/L. File I/O. File Processing. Gabriel Hugh Elkaim Winter File Processing. Files and Streams. Outline.
CMPE-013/L Outline File Processing File I/O Gabriel Hugh Elkaim Winter 2014 Files and Streams Open and Close Files Read and Write Sequential Files Read and Write Random Access Files Read and Write Random
More informationIntroduction to Computer and Program Design. Lesson 6. File I/O. James C.C. Cheng Department of Computer Science National Chiao Tung University
Introduction to Computer and Program Design Lesson 6 File I/O James C.C. Cheng Department of Computer Science National Chiao Tung University File System in OS Microsoft Windows Filename DriveID : /DirctoryName/MainFileName.ExtensionName
More informationModule 11 The C++ I/O System
Table of Contents Module 11 The C++ I/O System CRITICAL SKILL 11.1: Understand I/O streams... 2 CRITICAL SKILL 11.2: Know the I/O class hierarchy... 3 CRITICAL SKILL 11.3: Overload the > operators...
More informationSystem Software Experiment 1 Lecture 7
System Software Experiment 1 Lecture 7 spring 2018 Jinkyu Jeong ( jinkyu@skku.edu) Computer Systems Laboratory Sungyunkwan University http://csl.skku.edu SSE3032: System Software Experiment 1, Spring 2018
More informationObject Oriented Programming Using C++ UNIT-3 I/O Streams
File - The information / data stored under a specific name on a storage device, is called a file. Stream - It refers to a sequence of bytes. Text file - It is a file that stores information in ASCII characters.
More informationStreams - Object input and output in C++
Streams - Object input and output in C++ Dr. Donald Davendra Ph.D. Department of Computing Science, FEI VSB-TU Ostrava Dr. Donald Davendra Ph.D. (Department of Computing Streams - Object Science, input
More informationDocumentation. Programming / Documentation Slide 42
Documentation http://www.math.upb.de/~robsy/lehre/programmierkurs2008/ Programming / Documentation Slide 42 Memory Management (I) There are several types of memory which a program can access: Stack Every
More informationC++ does not, as a part of the language, define how data are sent out and read into the program
Input and Output C++ does not, as a part of the language, define how data are sent out and read into the program I/O implementation is hardware dependent The input and output (I/O) are handled by the standard
More informationCOMP322 - Introduction to C++
COMP322 - Introduction to C++ Lecture 05 - I/O using the standard library, stl containers, stl algorithms Dan Pomerantz School of Computer Science 5 February 2013 Basic I/O in C++ Recall that in C, we
More informationStreams in C++ Stream concept. Reference information. Stream type declarations
Stream concept A stream represent a sequence of bytes arriving, being retrieved, being stored, or being sent, in order. A stream is continuos and offer sequential access to the data. Each byte can be read
More informationIntroduction. Lecture 5 Files and Streams FILE * FILE *
Introduction Lecture Files and Streams C programs can store results & information permanently on disk using file handling functions These functions let you write either text or binary data to a file, and
More informationStudy Material for Class XII. Data File Handling
Study Material for Class XII Page 1 of 5 Data File Handling Components of C++ to be used with handling: Header s: fstream.h Classes: ifstream, ofstream, fstream File modes: in, out, in out Uses of cascaded
More informationStream States. Formatted I/O
C++ Input and Output * the standard C++ library has a collection of classes that can be used for input and output * most of these classes are based on a stream abstraction, the input or output device is
More informationFundamental File Processing Operations 2. Fundamental File Processing Operations
2 Fundamental File Processing Operations Copyright 2004, Binnur Kurt Content Sample programs for file manipulation Physical files and logical files Opening and closing files Reading from files and writing
More informationios ifstream fstream
File handling in C++ In most of the real time programming problems we need to store the data permanently on some secondary storage device so that it can be used later. Whenever we have to store the data
More informationUNIT IV-2. The I/O library functions can be classified into two broad categories:
UNIT IV-2 6.0 INTRODUCTION Reading, processing and writing of data are the three essential functions of a computer program. Most programs take some data as input and display the processed data, often known
More informationCSC 138 Structured Programming CHAPTER 4: TEXT FILE [PART 1]
CSC 138 Structured Programming CHAPTER 4: TEXT FILE [PART 1] LEARNING OBJECTIVES Upon completion, you should be able to: o define C++ text files o explain the benefits of using I/O file processing o explain
More informationOutline. Introduction. Arrays declarations and initialization. Const variables. Character arrays. Static arrays. Examples.
Outline Introduction. Arrays declarations and initialization. Const variables. Character arrays. Static arrays. Examples. 1 Arrays I Array One type of data structures. Consecutive group of memory locations
More informationChapter 12: Advanced File Operations
Chapter 12: Advanced File Operations 12.1 File Operations File Operations File: a set of data stored on a computer, often on a disk drive Programs can read from, write to files Used in many applications:
More informationUEE1303(1070) S 12 Object-Oriented Programming in C++
Computational Intelligence on Automation Lab @ NCTU Learning Objectives UEE1303(1070) S 12 Object-Oriented Programming in C++ Lecture 06: Streams and File Input/Output I/O stream istream and ostream member
More informationAdvanced File Operations. Review of Files. Declaration Opening Using Closing. CS SJAllan Chapter 12 2
Chapter 12 Advanced File Operations Review of Files Declaration Opening Using Closing CS 1410 - SJAllan Chapter 12 2 1 Testing for Open Errors To see if the file is opened correctly, test as follows: in.open("cust.dat");
More informationCS201 Solved MCQs.
15.1 Answer each of the following: a. Input/output in C++ occurs as of bytes. b. The stream manipulators that format justification are, and. c. Member function can be used to set and reset format state.
More informationBBM#101# #Introduc/on#to# Programming#I# Fall$2013,$Lecture$13$
BBM#101# #Introduc/on#to# Programming#I# Fall$2013,$Lecture$13$ Today#! File#Input#and#Output#! Strings#! Data!Files!! The!Data!Type!char!! Data!Hierarchy!! Characters!and!Integers!! Files!and!Streams!!
More informationFiles and Streams Opening and Closing a File Reading/Writing Text Reading/Writing Raw Data Random Access Files. C File Processing CS 2060
CS 2060 Files and Streams Files are used for long-term storage of data (on a hard drive rather than in memory). Files and Streams Files are used for long-term storage of data (on a hard drive rather than
More informationbasic_fstream<chart, traits> / \ basic_ifstream<chart, traits> basic_ofstream<chart, traits>
The C++ I/O System I/O Class Hierarchy (simplified) ios_base ios / \ istream ostream \ / iostream ifstream fstream ofstream The class ios_base -- public variables and methods The derived classes istream,
More informationC programming basics T3-1 -
C programming basics T3-1 - Outline 1. Introduction 2. Basic concepts 3. Functions 4. Data types 5. Control structures 6. Arrays and pointers 7. File management T3-2 - 3.1: Introduction T3-3 - Review of
More informationFiles. Programs and data are stored on disk in structures called files Examples. a.out binary file lab1.c - text file term-paper.
File IO part 2 Files Programs and data are stored on disk in structures called files Examples a.out binary file lab1.c - text file term-paper.doc - binary file Overview File Pointer (FILE *) Standard:
More informationChapter 12. Streams and File I/O. Copyright 2016 Pearson, Inc. All rights reserved.
Chapter 12 Streams and File I/O Copyright 2016 Pearson, Inc. All rights reserved. Learning Objectives I/O Streams File I/O Character I/O Tools for Stream I/O File names as input Formatting output, flag
More informationChapter 12. Streams and File I/O. Copyright 2010 Pearson Addison-Wesley. All rights reserved
Chapter 12 Streams and File I/O Copyright 2010 Pearson Addison-Wesley. All rights reserved Learning Objectives I/O Streams File I/O Character I/O Tools for Stream I/O File names as input Formatting output,
More informationDarshan Institute of Engineering & Technology for Diploma Studies Unit 6
1. What is File management? In real life, we want to store data permanently so that later on we can retrieve it and reuse it. A file is a collection of bytes stored on a secondary storage device like hard
More informationBBM#101# #Introduc/on#to# Programming#I# Fall$2014,$Lecture$13$
BBM#101# #Introduc/on#to# Programming#I# Fall$2014,$Lecture$13$ Today#! File#Input#and#Output#! Strings#! Data&Files&! The&Data&Type&char&! Data&Hierarchy&! Characters&and&Integers&! Files&and&Streams&!
More informationChapter 4 - Arrays. 4.1 Introduction. Arrays Structures of related data items Static entity (same size throughout program) A few types
Chapter 4 - Arrays 1 4.1 Introduction 4.2 Arrays 4.3 Declaring Arrays 4.4 Examples Using Arrays 4.5 Passing Arrays to Functions 4.6 Sorting Arrays 4.7 Case Study: Computing Mean, Median and Mode Using
More informationC++ How to Program 14.6
C++ How to Program 14.6 14.6 Random-Access Files pg.611-pg.612 -Unlike sequential files, R.A. files are instant-access applications. Any transaction-processing system. Requiring rapid access to specific
More informationProgram Design (II): Quiz2 May 18, 2009 Part1. True/False Questions (30pts) Part2. Multiple Choice Questions (40pts)
Class: No. Name: Part1. True/False Questions (30pts) 1. Function fscanf cannot be used to read data from the standard input. ANS: False. Function fscanf can be used to read from the standard input by including
More informationPiyush Kumar. input data. both cout and cin are data objects and are defined as classes ( type istream ) class
C++ IO C++ IO All I/O is in essence, done one character at a time For : COP 3330. Object oriented Programming (Using C++) http://www.compgeom.com/~piyush/teach/3330 Concept: I/O operations act on streams
More informationFile I/O Christian Schumacher, Info1 D-MAVT 2013
File I/O Christian Schumacher, chschuma@inf.ethz.ch Info1 D-MAVT 2013 Input and Output in C++ Stream objects Formatted output Writing and reading files References General Remarks I/O operations are essential
More informationBBM 101 Introduc/on to Programming I Fall 2013, Lecture 13
BBM 101 Introduc/on to Programming I Fall 2013, Lecture 13 Instructors: Aykut Erdem, Erkut Erdem, Fuat Akal TAs: Yasin Sahin, Ahmet Selman Bozkir, Gultekin Isik 1 Today File Input and Output Strings Data
More informationcs3157: c++ lecture #2 (mon-11-apr-2005) chronology of some programming languages... C++ vs Java identifiers.
cs3157: c++ lecture #2 (mon-11-apr-2005) chronology of some programming languages... today: language basics: identifiers, data types, operators, type conversions, branching and looping, program structure
More informationPIC10B/1 Winter 2014 Exam I Study Guide
PIC10B/1 Winter 2014 Exam I Study Guide Suggested Study Order: 1. Lecture Notes (Lectures 1-8 inclusive) 2. Examples/Homework 3. Textbook The midterm will test 1. Your ability to read a program and understand
More informationWriting a Good Program. 7. Stream I/O
Writing a Good Program 1 Input and Output I/O implementation is hardware dependent C++ does not, as a part of the language, define how data are sent out and read into the program The input and output (I/O)
More informationClasses and Objects. Instructor: 小黑
Classes and Objects Instructor: 小黑 Files and Streams in C : 1 #include 2 3 4 int main( void ) { 5 char input[ 5 ]; 6 7 FILE *cfptr; 8 9 if (( cfptr = fopen( a.txt", r )) == NULL ) { 10 printf(
More informationObject Oriented Programming
Object Oriented Programming Course Title: Object Oriented Programming Full Marks: 60 20 20 Course No: CSC161 Pass Marks: 24 8 8 Nature of Course: Theory Lab Credit Hrs: 3 Semester: II Course Description:
More informationC Input/Output. Before we discuss I/O in C, let's review how C++ I/O works. int i; double x;
C Input/Output Before we discuss I/O in C, let's review how C++ I/O works. int i; double x; cin >> i; cin >> x; cout
More informationIntroduction to C++ (Extensions to C)
Introduction to C++ (Extensions to C) C is purely procedural, with no objects, classes or inheritance. C++ is a hybrid of C with OOP! The most significant extensions to C are: much stronger type checking.
More informationChapte t r r 9
Chapter 9 Session Objectives Stream Class Stream Class Hierarchy String I/O Character I/O Object I/O File Pointers and their manipulations Error handling in Files Command Line arguments OOPS WITH C++ Sahaj
More information