Chapter 9 – File Input Output

Slides:



Advertisements
Similar presentations
Files in C Rohit Khokher. Files in C Real life situations involve large volume of data and in such cases, the console oriented I/O operations pose two.
Advertisements

Memory and Files Dr. Andrew Wallace PhD BEng(hons) EurIng
CSCI 171 Presentation 12 Files. Working with files File Streams – sequence of data that is connected with a specific file –Text Stream – Made up of lines.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved Introduction Data files –Can be created, updated,
 2000 Prentice Hall, Inc. All rights reserved. Chapter 11 – File Processing Outline 11.1Introduction 11.2The Data Hierarchy 11.3Files and Streams 11.4Creating.
Chapter 11 C File Processing Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education Inc.
1 Homework Introduction to HW7 –Complexity similar to HW6 –Don’t wait until last minute to start on it File Access will be needed in HW8.
A First Book of ANSI C Fourth Edition Chapter 10 Data Files.
Lone Leth Thomsen Input / Output and Files. April 2006Basis-C-8/LL2 sprintf() and sscanf() The functions sprintf() and sscanf() are string versions of.
22. FILE INPUT/OUTPUT. File Pointers and Streams Declarations of functions that perform file I/O appear in. Each function requires a file pointer as a.
File Handling In C By - AJAY SHARMA. We will learn about- FFile/Stream TText vs Binary Files FFILE Structure DDisk I/O function OOperations.
 2007 Pearson Education, Inc. All rights reserved C File Processing.
File IO and command line input CSE 2451 Rong Shi.
1 Lecture09: File I/O 11/19/2012 Slides modified from Yin Lou, Cornell CS2022: Introduction to C.
Memory Layout, File I/O Bryce Boe 2013/06/27 CS24, Summer 2013 C.
Chapter 11: Data Files and File Processing Files and streams Creating a sequential access file Reading data from a sequential access file Using fgetc()
Chapter 11 File Processing. Objectives In this chapter, you will learn: –To be able to create, read, write and update files. –To become familiar with.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 11 – File Processing Outline 11.1Introduction.
Chapter 12 Files (reference: Deitel ’ s chap 11) chap8.
Chapter 7 : File Processing1 File-Oriented Input & Output CHAPTER 7.
1 CHAPTER6 CHAPTER 6. Objectives: You’ll learn about;  Introduction  Files and streams  Creating a sequential access file  Reading data from a sequential.
Lecture 11: Files & Arrays B Burlingame 18 November 2015.
CNG 140 C Programming (Lecture set 10) Spring Chapter 10 Data Files.
FILE IO in ‘C’ by Dr P.Padmanabham Professor (CSE)&Director Bharat Institute of Engineering &Technology Hyderabad Mobile
24-2 Perform File I/O using file pointers FILE * data-type Opening and closing files Character Input and Output String Input and Output Related Chapter:
chap8 Chapter 12 Files (reference: Deitel ’ s chap 11)
GAME203 – C Files stdio.h C standard Input/Output “getchar()”
Files A collection of related data treated as a unit. Two types Text
 2007 Pearson Education, Inc. All rights reserved. 1 C File Processing.
FILES IN C. File Operations  Creation of a new file  Opening an existing file  Reading from a file  Writing to a file  Moving to a specific location.
Files. FILE * u In C, we use a FILE * data type to access files. u FILE * is defined in /usr/include/stdio.h u An example: #include int main() { FILE.
Connecting to Files In order to read or write to a file, we need to make a connection to it. There are several functions for doing this. fopen() – makes.
C Programming Day 2. 2 Copyright © 2005, Infosys Technologies Ltd ER/CORP/CRS/LA07/003 Version No. 1.0 Union –mechanism to create user defined data types.
Advanced Programming in the UNIX Environment Hop Lee.
 2007 Pearson Education, Inc. All rights reserved C File Processing.
6/9/2016Course material created by D. Woit 1 CPS 393 Introduction to Unix and C START OF WEEK 10 (C-4)
Real Numbers Device driver process within the operating system that interacts with I/O controller logical record 1 logical record 2 logical record 3.
11 C File Processing.
Chapter 22 – part a Stream refer to any source of input or any destination for output. Many small programs, obtain all their input from one stream usually.
Lecture 11 File input/output
TMF1414 Introduction to Programming
File I/O.
CSC215 Lecture Input and Output.
Plan for the Day: I/O (beyond scanf and printf)
CS111 Computer Programming
CSE1320 Files in C Dr. Sajib Datta
File Input/Output.
CSE1320 Files in C Dr. Sajib Datta
Programming in C Input / Output.
Files I/O, Streams, I/O Redirection, Reading with fscanf
File I/O We are used to reading from and writing to the terminal:
Chapter 11 – File Processing
Chapter 14 - Advanced C Topics
Beginning C Lecture 11 Lecturer: Dr. Zhao Qinpei
FILE HANDLING IN C.
Text and Binary File Processing
File Input and Output.
Accessing Files in C Professor Hugh C. Lauer CS-2303, System Programming Concepts (Slides include materials from The C Programming Language, 2nd edition,
Fundamental of Programming (C)
Line at a time I/O with fgets() and fputs()
Programming in C Input / Output.
EPSII 59:006 Spring 2004.
Module 12 Input and Output
File I/O & UNIX System Interface
CSc 352 File I/O Saumya Debray Dept. of Computer Science
Professor Jodi Neely-Ritz University of Florida
I/O CS580U - Fall 2018.
Professor Jodi Neely-Ritz University of Florida
File I/O We are used to reading from and writing to the terminal:
Chapter 18 I/O in C.
Presentation transcript:

Chapter 9 – File Input Output Introduction to pointers stream buffer C language stream interface C stream library Reading and writing data to file 1

What is a pointer? Why use pointers? pointers are different from other variables that we have defined previously in that they contain ONLY the address (location in memory) of a variable. pointers are unsigned quantities! used for simulated pass by reference. used to dynamically allocate memory. used to interface with embedded controllers

POINTER declaration pointers point to specific data types ONLY an asterisk in front of a variable name (identifier) indicates that it is a pointer: char *ptr_c int *ptr_i float * ptr_f double *henry

POINTER comments Pointers take up the same amount of memory, regardless of the data type they point to. usually 4 bytes in 32 bit machines Pointers can not be used to point to other data types (Why? wait for pointer arithmetic) Pointers follow usual initialization rules (and contain garbage if automatic scope). global pointers set to zero, which represents null

More POINTER comments the asterisk is associated with the name: (1) char *ptr1, ptr2 (2) char* ptr1, *ptr2 (3) char *ptr1, *ptr2 prt1 is always a pointer, ptr2 is NOT a pointer in (1). approach (3) is preferred.

lvalues and rvalues Consider the declaration: int count = 5; assume that count is stored in memory location 0x07A3. the rvalue is the data that the variable holds: in our case 5 the lvalue is the address where the data is stored: in our case 0x07A3.

POINTER initialization From scanf, we know that placing an ampersand (&) in front of a variable means “address of ” (hence it is the address operator). We can use this idea to initialize pointers: int *count_ptr = &count; Now the rvalue of count_ptr is the lvalue of count (0x07A3) and the lvalue of count_ptr is the address of count_ptr.

Still more POINTER comments Some compilers may only produce warnings if you initialize a pointer with the wrong data type. Pointers can be printed with %p (or %x) format. Pointers can be declared “register” variables. Pointers can not take the address of: register variables implicit constants expressions

indirection (deferencing) operator a pointer can be used to retrieve the rvalue of the variable that it is pointing to with the indirection operator (*) WARNING: the asterisks serves three functions: multiplication, pointer definition and indirection. The indirection operator * can be thought of as inverse of address operator &

Program 9.1 - simple examples /* Program #9.1, last modified Oct. 20, 1996 This is a simple demonstration of pointers */ #include <stdio.h> int main(void) { int count=5; int *count_ptr=&count; printf("for count , rvalue=%d; lvalue=%p\n",count,count_ptr); printf("for count , rvalue=%d; lvalue=%x\n",*count_ptr,&count); printf("for count , rvalue=%d; lvalue=%x\n",*&count,&*count_ptr); printf("for count_ptr, rvalue=%p; lvalue=%x\n",count_ptr,&count_ptr); return 0; }

Data Streams Goals: Approach: to improve portability and reuse of codes. to select the input/output hardware at run time. Approach: communicate with peripheral devices in a uniform and consistent way. write input and output (I/O) functions, e.g. fscanf and fprintf, so that they are independent of the peripheral devices. write device drivers to interface between I/O and the actual devices.

Stream buffer and device interfaces location in memory set aside to be transfer point to and from a device. Usually has a fixed size which depends on the device. (Stream) input buffer - when read occurs: data is input from buffer. When buffer is empty, more data is taken from device and placed in buffer. e.g. for a keyboard, buffer contains all keystrokes.

Stream buffers - continued (Stream) output buffer - when write occurs: data is output to buffer. When buffer is full, data is written to device. Actually, there are 3 possibilities: full buffering (described above - good for disk files). often set by BUFSIZ - typically 256, 512, or 1024 bytes. line buffering: (data is written when a newline \n is encountered - good for printer). no buffering - (sometimes necessary)

C language stream interface Recall the FILE data type that we used to declare a pointer for disk operations. FILE is a structure defined in <stdio.h> The details of structure are not important, though they are given on following slide. These structures usually reside within the operating system kernal (core program) in the stream I/O manager. Typically about 20 files can be opened, the first three are reserved for stdin, stdout, and stderr.

Typical FILE structure #define MAX_FILE_NUM 20 typedef struct { int level; /* full or empty level of stream buffer */ unsigned flags; /* Stream status flag */ char path; /* Stream descriptor */ unsigned char hold; /* To hold unget char if no buffer */ int bsize; /* Size of buffer for stream */ unsigned char *buffer; /* Pointer to stream buffer */ unsigned char *nextc; /* Pointer to next char in buffer */ unsigned tempfile; /* Temporary file flag */ } FILE; extern FILE _iob[MAX_FILE_NUM ] /* located in OS kernal */

The C stream library We will describe some but definitely not all: Stream creation and control: fopen(), freopen(), fclose(), fflush(), setbuf(), setvbuf(), tmpfile(); Stream read/write: fprintf(), fputs(), fputc(), fscanf(), fgets(), fgetc(), ungetc(), read(), write(); Stream positioning: fgetpos(), fsetpos(), fseek(), rewind(), ftell(); Stream error functions: feof(), ferror(), cleareff(), strerror(), perror(); miscillaneous: rename(), remove(), tmpnam();

fopen() - creating/opening a stream fopen connects a stream with a physical device an element from _iob[] array is allocated to the program and a pointer of the type FILE is returned to it. A NULL pointer is returned if there is an error opening the file. The prototype for fopen in <stdio.h> is: FILE *fopen(const char *name, const char *mode); name is the pathlist / device name mode deals with allowed operations (read, write...)

Valid mode parameters for text files “r” Open an existing file for reading only. “r+” Open an existing file for reading and writing. “w” Create a non existent file or open but truncate an existing file for writing. “w+” Create a non existent file file for writing & reading. “a” Open a file for appending at the end or create it if it doesn’t exist. “a+” Open a file for appending (for reading & writing).

Difference between r+, w+, & a+ these three modes all allow reading and writing but: for r+ an error occurs if file does not exist. for r+ the existing data is not discarded, but can be overwritten with random access. for w+ the existing data (if any) is always discarded. for a+ the existing data (if any) is not discarded and can not be overwritten, even with random access - data is always written at end of file.

SP indicators and EOF markers The stream position indicator points to the next character in the stream. The end-of-file marker points points just past the (current) end of the file. for “r” mode SPI is set to the file beginning and EOF is set to the end. for “w” mode, SPI and EOF set to file beginning. for “a” mode, SPI and EOF set to file end.

fprintf() - formatted file print function prototype in <stdio.h> : int fprintf(FILE *stream, const char *format, ...); returns the number of characters written to the stream or EOF for an error. NOTE: stream is typically buffered, and errors don’t usually occur until the device is accessed. Beware! stream is the file pointer returned by fopen. format is the printf compatible format string. the ellipsis indicates the arguments to be printed.

fscanf() - formatted file scan function prototype in <stdio.h> : int fscanf(FILE *stream, const char *format, ...); returns the number of objects read from the stream or EOF for an error or end-of-file. EOF returned only if NO data succesfully read cause of error can be found from ferror() or feof(). error can be cleared with clearerr() or rewind(). stream is the file pointer returned by fopen. format is the printf compatible format string. the ellipsis indicates argument addresses to be scaned.

fclose() - closing a stream function prototype in <stdio.h> : int fclose(FILE *stream); returns an EOF if error is encountered during close. any unread data in buffer is discarded any unwritten data is sent to device stream is the file pointer returned by fopen. releases _iob[] for use by another file

fflush() - flushing a stream function prototype in <stdio.h>: int fflush(FILE *stream); returns an EOF if error is encountered during flush. any unread data in buffer is discarded. particularly useful when fscanf has an error. any unwritten data is sent to device. stream is the file pointer returned by fopen.

perror() function prototypes in <stdio.h> : void perror(const char *message); perror prints the message to the default error stream (stderr)

Program 9.2 - part 1 /* write, append, and read values of sin(x) to disk */ #include <stdio.h> #include <stdlib.h> #include <errno.h> #include <math.h> #define PI 3.1415927 int main( void ) { FILE *f1, *fp1, *fp2; double count, temp_sin ;

Program 9.2 - part 2 /* write sin(x) from 0 to PI/2 */ if( (f1 = fopen( "sine.dat" , "w")) == NULL) { printf("Error cannot open file sine.dat for writing....." ) ; exit( EXIT_FAILURE ) ; } for( count = 0 ; count < PI/2 ; count += 0.01 ) { if( fprintf( f1 , "Sine of %6.3g radians = %8.6g\n" , count, sin( count )) ==EOF) { printf("Error writing out file sine.dat..... ") ; if( fclose( f1 ) ) printf("Error Closing File sine.dat.....") ;

Program 9.2 - part 3 /* append sin(x) from PI/2 to PI */ if( (f1 = fopen( "sine.dat" , "a")) == NULL) { printf("Error cannot open file sine.dat for appending....." ) ; exit( EXIT_FAILURE ) ; } for( count = PI/2 ; count < PI ; count += 0.01 ) { if( fprintf( f1 ,"Sine of %6.3g radians = %8.6g\n", count, sin( count )) ==EOF) { printf("Error appending out file sine.dat..... ") ; if( fclose( f1 ) ) printf("Error Closing File sine.dat.....") ;

Program 9.2 - part 4 /* read and print sin(x), cos(x) and tan(x) from 0 to PI (to another file)*/ if( (fp1 = fopen("sine.dat" , "r")) == NULL ) { printf("Error opening File sine.dat..... ") ; exit( EXIT_FAILURE ) ; } if( (fp2 = fopen("sctan.dat" , "w")) == NULL ) { printf("Error opening File sctan.dat .....") ;

Program 9.2 - final part while( 1 ) { if( fscanf( fp1, "Sine of %lf radians = %lf\n" , &count, &temp_sin) != 2) break ; if( fprintf( fp2,"%f %f %f %f\n", count, temp_sin, cos(count), tan(count)) == EOF ) } if( ferror( fp1 )) printf("Error Reading File sine.dat.....") ; if( fclose( fp2 )) printf("Error Writing to File sctan.dat.....") ; return 0 ;

Program 9.3 - part 1 /* perform a bubble sort of an integer array from high to low*/ #include <stdio.h> #include <stdlib.h> int main(int argc, char *argv[]) { FILE *File_in, *File_out; int num[100], i, j, temp, count=0; // input all of the integers that we are going to sort if( (File_in = fopen( argv[1] , "r")) == NULL) { perror("Error cannot open file for reading....." ) ; exit( EXIT_FAILURE ) ; }

Program 9.3 - part 2 while( 1 ) { if( fscanf( File_in, "%i\n" , &temp) != 1) break ; num[count++]=temp; } // print array before we start to sort printf("\n\nThe unsorted array is:\n"); for(i=0;i<count;i++) printf("%c %d",i%10?' ':'\n',num[i]);

Program 9.3 - part 3 // sort for(j=0;j<count-1;j++) { for(i=j+1;i<count;i++) if(num[i]>num[j]) { temp=num[i]; num[i]=num[j]; num[j]=temp; } if( fclose( File_in ) ) perror("Error closing file.....") ;

Program 9.3 - part 4 if( fclose( File_in ) ) perror("Error closing file .....") ; if( (File_out = fopen( argv[2] , "w")) == NULL) { perror("Error cannot open file for writing....." ) ; exit( EXIT_FAILURE ) ; }

Program 9.3 - final part // finished sort high to low; print results printf("\n\nThe SORTED array is:\n"); fprintf(File_out,"\n\nThe SORTED array is:\n"); for(i=0;i<count;i++) { printf("%c %d",i%10?' ':'\n',num[i]); fprintf(File_out,"%c %d",i%10?' ':'\n',num[i]); } printf("\n\n"); if( fclose( File_out ) ) perror("Error closing file.....") ; return 0;

fgets() - file string read function prototype (in <stdio.h>): char *fgets (char *buff, int num, FILE *stream); buff points to the string read from stream. returns pointer to buff if successful; NULL else. fgets stops reading from stream either when a \n is encountered or after reading num characters.

fgets() - continued if num terminates string read, the next read from the stream starts where fgets stopped. No data from the end of the line is lost! fgets should typically be used instead of gets to avoid potential errors with invalid data. unlike gets, fgets places a null (\0) after the \n. for dynamic allocation, use sizeof(strlen(buff)+1) (Why?)

fputs() - file string write function prototype (in <stdio.h>): int fputs (const char *buff, FILE *stream); buff points to the string written to the stream. returns zero if successful; EOF else. fputs differs from puts in that it does not append a \n at the end of the string. fputs should be used in conjunction with fgets.

fgetc() - file character read function prototype (in <stdio.h>): int fgetc (FILE *stream); returns an integer (corresponding to a character) from the stream if successful, EOF else. returns an integer rather than a character to avoid potential problems of a comparison with EOF, which is an integer constant.

fputc() - file character write function prototype (in <stdio.h>): int fputc (int c, FILE *stream); writes c to the stream. returns the (integer) c if successful, EOF else. returns an integer rather than a character to avoid potential problems of a comparison with EOF, which is an integer constant.

ungetc() - character return to stream function prototype (in <stdio.h>): int ungetc (int c, FILE *stream); pushes the integer c (corresponding to a character) back onto the stream. returns the integer c if successful, EOF else. Why? sometimes you don’t know that you’ve read too far until it’s too late. Only one ungetc is guaranteed in ANSI C.