C File Processing: One-Page Summary

Similar documents
Lecture 8. Dr M Kasim A Jalil. Faculty of Mechanical Engineering UTM (source: Deitel Associates & Pearson)

Chapter 11 File Processing

Chapter 12. Files (reference: Deitel s chap 11) chap8

Ch 11. C File Processing (review)

Lecture6 File Processing

File Processing. Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan

ENG120. Misc. Topics

C: How to Program. Week /June/18

STRUCTURES & FILE IO

BBM#101# #Introduc/on#to# Programming#I# Fall$2014,$Lecture$13$

BBM#101# #Introduc/on#to# Programming#I# Fall$2013,$Lecture$13$

C How to Program, 6/e by Pearson Education, Inc. All Rights Reserved.

BBM 101 Introduc/on to Programming I Fall 2013, Lecture 13

Introduction to Computer Programming Lecture 18 Binary Files

LAB 13 FILE PROCESSING

LAB 13 FILE PROCESSING

Chapter 8 File Processing

Lecture 9: File Processing. Quazi Rahman

Files and Streams Opening and Closing a File Reading/Writing Text Reading/Writing Raw Data Random Access Files. C File Processing CS 2060

Fundamentals of Programming. Lecture 15: C File Processing

CMPE-013/L. File I/O. File Processing. Gabriel Hugh Elkaim Winter File Processing. Files and Streams. Outline.

Computer programming

System Software Experiment 1 Lecture 7

Accessing Files in C. Professor Hugh C. Lauer CS-2303, System Programming Concepts

Chapter 12. Text and Binary File Processing. Instructor: Öğr. Gör. Okan Vardarlı. Copyright 2004 Pearson Addison-Wesley. All rights reserved.

UNIT IV-2. The I/O library functions can be classified into two broad categories:

Mode Meaning r Opens the file for reading. If the file doesn't exist, fopen() returns NULL.

Standard File Pointers

C for Engineers and Scientists: An Interpretive Approach. Chapter 14: File Processing

Darshan Institute of Engineering & Technology for Diploma Studies Unit 6

PROGRAMMAZIONE I A.A. 2017/2018

Content. Input Output Devices File access Function of File I/O Redirection Command-line arguments

Fundamentals of Programming Session 28

File I/O. Arash Rafiey. November 7, 2017

CS240: Programming in C

CSci 4061 Introduction to Operating Systems. Input/Output: High-level

C PROGRAMMING. Characters and Strings File Processing Exercise

Standard C Library Functions

Systems Programming. 08. Standard I/O Library. Alexander Holupirek

Sistemas Operativos /2016 Support Document N o 1. Files, Pipes, FIFOs, I/O Redirection, and Unix Sockets

CSI 402 Lecture 2 Working with Files (Text and Binary)

Introduction to Computer and Program Design. Lesson 6. File I/O. James C.C. Cheng Department of Computer Science National Chiao Tung University

Input / Output Functions

Quick review of previous lecture Ch6 Structure Ch7 I/O. EECS2031 Software Tools. C - Structures, Unions, Enums & Typedef (K&R Ch.

C-Refresher: Session 10 Disk IO

25.2 Opening and Closing a File

Unit 6 Files. putchar(ch); ch = getc (fp); //Reads single character from file and advances position to next character

CS246 Spring14 Programming Paradigm Files, Pipes and Redirection

C Basics And Concepts Input And Output

Intermediate Programming, Spring 2017*

File IO and command line input CSE 2451

Input/Output and the Operating Systems

Programming & Data Structure

Files. Programs and data are stored on disk in structures called files Examples. a.out binary file lab1.c - text file term-paper.

Data File and File Handling

EM108 Software Development for Engineers

2009 S2 COMP File Operations

UNIX System Programming

fopen() fclose() fgetc() fputc() fread() fwrite()

Program Design (II): Quiz2 May 18, 2009 Part1. True/False Questions (30pts) Part2. Multiple Choice Questions (40pts)

CE Lecture 11

C programming basics T3-1 -

MARKS: Q1 /20 /15 /15 /15 / 5 /30 TOTAL: /100

File (1A) Young Won Lim 11/25/16

UNIT-V CONSOLE I/O. This section examines in detail the console I/O functions.

Preprocessing directives are lines in your program that start with `#'. The `#' is followed by an identifier that is the directive name.

IS 0020 Program Design and Software Tools

BIL 104E Introduction to Scientific and Engineering Computing. Lecture 12

Goals of this Lecture

Introduction to file management

I/O Management! Goals of this Lecture!

C Programming Language

I/O Management! Goals of this Lecture!

Naked C Lecture 6. File Operations and System Calls

C Programming 1. File Access. Goutam Biswas. Lect 29

File I/O. Preprocessor Macros

Computer Programming

Computer Programming Unit v

DS: CS Computer Sc & Engg: IIT Kharagpur 1. File Access. Goutam Biswas. ect 29

What Is Operating System? Operating Systems, System Calls, and Buffered I/O. Academic Computers in 1983 and Operating System

C Input/Output. Before we discuss I/O in C, let's review how C++ I/O works. int i; double x;

Organization of a file

Fundamentals of Programming. Lecture 10 Hamed Rasifard

CSI 402 Lecture 2 (More on Files) 2 1 / 20

Programming in C. Session 8. Seema Sirpal Delhi University Computer Centre

C Syntax Arrays and Loops Math Strings Structures Pointers File I/O. Final Review CS Prof. Jonathan Ventura. Prof. Jonathan Ventura Final Review

Basic I/O. COSC Software Tools. Streams. Standard I/O. Standard I/O. Formatted Output

Computer System and programming in C

Lecture 9. Introduction

Physical Files and Logical Files. Opening Files. Chap 2. Fundamental File Processing Operations. File Structures. Physical file.

CS 261 Fall Mike Lam, Professor. Structs and I/O

Week 9 Lecture 3. Binary Files. Week 9

Day14 A. Young W. Lim Tue. Young W. Lim Day14 A Tue 1 / 15

CSCI 171 Chapter Outlines

CSI 402 Systems Programming LECTURE 4 FILES AND FILE OPERATIONS

File Handling. 21 July 2009 Programming and Data Structure 1

Day14 A. Young W. Lim Thr. Young W. Lim Day14 A Thr 1 / 14

Lecture 7: Files. opening/closing files reading/writing strings reading/writing numbers (conversion to ASCII) command line arguments

Topic 8: I/O. Reading: Chapter 7 in Kernighan & Ritchie more details in Appendix B (optional) even more details in GNU C Library manual (optional)

CS113: Lecture 7. Topics: The C Preprocessor. I/O, Streams, Files

Transcription:

Chapter 11 C File Processing C File Processing: One-Page Summary #include <stdio.h> int main() { int a; FILE *fpin, *fpout; if ( ( fpin = fopen( "input.txt", "r" ) ) == NULL ) printf( "File could not be opened\n" ); if ( ( fpout = fopen( "output.txt", "w" ) ) == NULL ) printf( "File could not be opened\n" ); while (!feof(fpin) ) { fscanf(fpin, "%d", &a); fprintf(fpout, "%d\n", a); fclose(fpin); fclose(fpout); 13 26 54 77 return 0; 13 26 54 77 1

Data Hierarchy Bit Byte Field Record File Database Record key Sequential file Fig. 11.3: Creating a Sequential File #include <stdio.h> int main() { int account; char name[30]; double balance; FILE *cfptr; if ( ( cfptr = fopen( "clients.dat", "w" ) ) == NULL ) printf( "File could not be opened\n" ); else { printf("enter the account, name, and balance.\n"); printf( "Enter EOF to end input.\n" ); printf( "? " ); scanf( "%d%s%lf", &account, name, &balance ); while (!feof( stdin ) ) { fprintf(cfptr,"%d %s %.2f\n",account,name,balance); printf( "? " ); scanf( "%d%s%lf", &account, name, &balance ); fclose( cfptr ); Enter the account, name, and balance. Enter EOF to end input.? 100 Jones 24.98? 200 Doe 345.67? 300 White 0.00? 400 Stone -42.16? 500 Rich 224.62? ^Z 2

Artificial Generation of EOF Markers Computer system Key combination UNIX systems <return> <ctrl> d IBM PC and compatibles <ctrl> z Macintosh <ctrl> d Fig. 11.4 End-of-file key combinations for various pop How C Views a File? C views each file as a sequence of bytes File ends with the end-of-file marker Or, file ends at a specified byte C imposes no file structure No notion of records in a file Programmer must provide file structure 3

Opening a File FILE *cfptr; Creates a FILE pointer called cfptr cfptr = fopen( clients.dat", w ); Function fopen returns a FILE pointer to file specified Takes two arguments file to open and file open mode If open fails, NULL returned Streams Stream created when a file is opened Provide communication channel between files and programs Opening a file returns a pointer to a FILE structure fptr normal file stdin - standard input (keyboard) stdout - standard output (screen) stderr - standard error (screen) 4

File Open Modes Mode r w a Description 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. rb wb ab rb+ wb+ ab+ Fig. 11.6 Open a file for reading in binary mode. Create a file for writing in binary mode. If the file already exists, discard the current contents. Append; open or create a file for writing at end of file in binary mode. Open a file for update (reading and writing) in binary mode. Create a file for update in binary mode. If the file already exists, discard the current contents. Append; open or create a file for update in binary mode; writing is done at the end of the file. File open modes. File Processing Functions in stdio 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 5

Other Stuff in stdio Library 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) 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 Use fscanf to read from the file Like scanf, except first argument is a FILE pointer rewind(cfptr) Repositions file position pointer to beginning of file (byte 0) Fig. 11.7: Reading and Printing a Seq. File #include <stdio.h> int main() { int account; /* account number */ char name[ 30 ]; /* account name */ double balance; /* account balance */ FILE *cfptr; if ((cfptr=fopen("clients.dat","r"))==null) printf( "File could not be opened\n" ); else { printf("%-10s%13s%s\n","account","name","balance"); fscanf(cfptr,"%d%s%lf",&account,name,&balance); while (!feof( cfptr ) ) { printf("%-10d%-13s%7.2f\n",account,name,balance); fscanf(cfptr,"%d%s%lf",&account,name,&balance); fclose( cfptr ); 6

Account Name Balance 100 Jones 24.98 200 Doe 345.67 300 White 0.00 400 Stone -42.16 500 Rich 224.62 Fig. 11.8: Credit Inquiry Program 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: 300 White 0.00? 2 Accounts with credit balances: 400 Stone -42.16? 3 Accounts with debit balances: 100 Jones 24.98 200 Doe 345.67 500 Rich 224.62? 4 End of run. 7

Modifying a Sequential Access File can be Risky Cannot be modified without the risk of destroying other data Fields can vary in size Different representation in files and screen than internal representation 1, 34, -890 are all ints, but have different sizes on disk 300 White 0.00 400 Jones 32.87 (old data in file) If we want to change White's name to Worthington, 300 Worthington 0.00 300 White 0.00 400 Jones 32.87 Data gets overwritten 300 Worthington 0.00ones 32.87 Random-Access Files In Random access files Access individual records without searching through other records Instant access to records in a file Data can be inserted without destroying other data Data previously stored can be updated or deleted without overwriting Implemented using fixed length records Sequential files do not have fixed length records 0 100 200 300 400 500 byte offsets 100 bytes 100 bytes 100 bytes 100 bytes 100 bytes 100 bytes 8

Fig. 11.11: Creating a Random Access File struct clientdata { int acctnum; /* account number */ char lastname[ 15 ]; /* account last name */ char firstname[ 10 ]; /* account first name */ double balance; /* account balance */ ; int main() { int i; struct clientdata blankclient = { 0, "", "", 0.0 ; FILE *cfptr; if (( cfptr = fopen("credit.dat", "wb" )) == NULL ) printf( "File could not be opened.\n" ); else { for ( i = 1; i <= 100; i++ ) fwrite(&blankclient,sizeof(struct clientdata), 1,cfPtr); fclose ( cfptr ); Data in Random Accessed Files Unformatted (stored as "raw bytes") All data of the same type (ints, for example) uses the same amount of memory All records of the same type have a fixed length Data not human readable 9

Unformatted I/O Functions fwrite Transfer bytes from a location in memory to a file fread Transfer bytes from a file to a location in memory Example: fwrite(&myobject, sizeof(struct mystruct), 3, myptr); &myobject Location to transfer bytes from sizeof(struct mystruct) Number of bytes to transfer 3 number of elements to transfer In this case, 3 objects of the struct type are transferred myptr File to transfer to or from Fig. 11.12: Writing to a Random Access File struct clientdata {...; int main() { FILE *cfptr; struct clientdata client = { 0, "", "", 0.0 ; if ((cfptr = fopen( "credit.dat", "rb+" )) == NULL) printf( "File could not be opened.\n" ); else { printf( "Enter account number" " ( 1 to 100, 0 to end input )\n? " ); scanf( "%d", &client.acctnum ); while ( client.acctnum!= 0 ) { printf("enter lastname,firstname,balance\n?"); fscanf( stdin, "%s%s%lf", client.lastname, client.firstname, &client.balance ); fseek( cfptr, ( client.acctnum - 1 ) * sizeof( struct clientdata ), SEEK_SET ); fwrite(&client,sizeof(struct clientdata),1,cfptr); /* enable user to input another account number */ printf( "Enter account number\n? " ); scanf( "%d", &client.acctnum ); fclose( cfptr ); 10

Enter account number ( 1 to 100, 0 to end input )? 37 Enter lastname, firstname, balance? Barker Doug 0.00 Enter account number? 29 Enter lastname, firstname, balance? Brown Nancy -24.54 Enter account number? 96 Enter lastname, firstname, balance? Stone Sam 34.98 Enter account number? 88 Enter lastname, firstname, balance? Smith Dave 258.34 Enter account number? 33 Enter lastname, firstname, balance? Dunn Stacey 314.33 Enter account number? 0 Writing Data to a Random Access File using fseek Sets file position pointer to a specific position fseek( pointer, offset, symbolic_constant ); pointer pointer to file offset file position pointer (0 is first location) symbolic_constant specifies where in file we are reading from SEEK_SET seek starts at beginning of file SEEK_CUR seek starts at current location in file SEEK_END seek starts at end of file 11

File Access Mechanism Fig. 11.15: Reading from a Random Access File struct clientdata {...; int main() { FILE *cfptr; struct clientdata client = { 0, "", "", 0.0 ; if ( ( cfptr = fopen( "credit.dat", "rb" ) ) == NULL ) printf( "File could not be opened.\n" ); else { printf( "%-6s%-16s%-11s%10s\n", "Acct", "Last Name", "First Name", "Balance" ); while (!feof( cfptr ) ) { fread(&client,sizeof(struct clientdata),1,cfptr); if ( client.acctnum!= 0 ) { printf( "%-6d%-16s%-11s%10.2f\n", client.acctnum, client.lastname, client.firstname, client.balance ); fclose( cfptr ); 12

Acct Last Name First Name Balance 29 Brown Nancy -24.54 33 Dunn Stacey 314.33 37 Barker Doug 0.00 88 Smith Dave 258.34 96 Stone Sam 34.98 Reading Data from a Randomly Accessed File using fread() fread Reads a specified number of bytes from a file into memory fread( &client, sizeof (struct clientdata), 1, myptr ); Can read several fixed-size array elements Provide pointer to array Indicate number of elements to read To read multiple elements, specify in the third argument 13

Fig. 11.16: A Transaction Processing Program This program Demonstrates using random access files to achieve instant access processing of a bank s account information We will Update existing accounts Add new accounts Delete accounts Store a formatted listing of all accounts in a text file Homework #11 No Homework for this chapter Due None No late submission is accepted! Submission Procedure Same as Homework #1 14

Chapter 11 C File Processing The End 15