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.

Slides:



Advertisements
Similar presentations
File Management in C. What is a File? A file is a collection of related data that a computers treats as a single unit. Computers store files to secondary.
Advertisements

Files in C Rohit Khokher.
BITS Pilani, Pilani Campus TA C252 Computer Programming - II Vikas Singh File Handling.
File Management in C. A file is a collection of related data that a computers treats as a single unit. File is a collection of data stored permanently.
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.
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,
Chapter 11 C File Processing Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education Inc.
Structures and Unions Chapter 6. Structure A structure is an aggregate data type  Composed of two or more related variables called member/field/element.
File I/O.
N305: C Programming Copyright ©2006  Department of Computer & Information Science File Handling in C.
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.
CP104 Introduction to Programming File I/O Lecture 33 __ 1 File Input/Output Text file and binary files File Input/output File input / output functions.
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.
 2007 Pearson Education, Inc. All rights reserved C File Processing.
1 Lecture09: File I/O 5/6/2013 Slides modified from Yin Lou, Cornell CS2022: Introduction to C.
Text and Binary File Processing 程式設計 潘仁義 CCU COMM.
Introduction to Programming Using C Files. 2 Contents Files Working with files Sequential files Records.
File IO and command line input CSE 2451 Rong Shi.
File I/O, Project 1: List ADT Bryce Boe 2013/07/02 CS24, Summer 2013 C.
ECE 103 Engineering Programming Chapter 44 File I/O Herbert G. Mayer, PSU CS Status 6/4/2014 Initial content copied verbatim from ECE 103 material developed.
1 File Handling. 2 Storage seen so far All variables stored in memory Problem: the contents of memory are wiped out when the computer is powered off Example:
1 Lecture09: File I/O 11/19/2012 Slides modified from Yin Lou, Cornell CS2022: Introduction to 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 Introduction Introduce some standard library functions.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 11 – File Processing Outline 11.1Introduction.
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.
Chapter 7 Files By C. Shing ITEC Dept Radford University.
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
C Programming Lecture 12 : File Processing
Structured Programming Approach Module VIII - Additional C Data Types File Handling Prof: Muhammed Salman Shamsi.
GAME203 – C Files stdio.h C standard Input/Output “getchar()”
Files A collection of related data treated as a unit. Two types Text
CSCI N305: C Programming Copyright ©2006  Department of Computer & Information Science File Handling in C.
CS 241 Section Week #5 9/22/11. 2 Topics This Section File I/O Advanced C.
 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.
Computer Science: A Structured Programming Approach Using C1 Objectives ❏ To understand the basic properties and characteristics of external files ❏ To.
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.
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.
Real Numbers Device driver process within the operating system that interacts with I/O controller logical record 1 logical record 2 logical record 3.
Silberschatz and Galvin  C Programming Language Kingdom of Saudi Arabia Ministry of Higher Education Al-Majma’ah University College of Education.
Lecture 12 CIS 208 Friday, March 3rd , 2005.
Chapter 4 File Processing
Lecture 11 File input/output
TMF1414 Introduction to Programming
Chapter 7 Text Input/Output Objectives
File I/O.
File Handling in C.
CS111 Computer Programming
What you need for the 1st phase of project
File Handling in C.
Chapter 11 – File Processing
Beginning C Lecture 11 Lecturer: Dr. Zhao Qinpei
FILE HANDLING IN C.
Text and Binary File Processing
File Input and Output.
File Handling.
Accessing Files in C Professor Hugh C. Lauer CS-2303, System Programming Concepts (Slides include materials from The C Programming Language, 2nd edition,
File Handling in C.
Fundamental of Programming (C)
A First Book of ANSI C Fourth Edition
Professor Jodi Neely-Ritz University of Florida
Presentation transcript:

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 on File (open,close,read,write rename etc.) FFormatted I/O function LLow level Disk I/O

What is a File ? A file is a collection of related data that a computers treats as a single unit. Computers store files to secondary storage so that the contents of files remain intact when a computer shuts down. When a computer reads a file, it copies the file from the storage device to memory; when it writes to a file, it transfers data from memory to the storage device

Cont… Files are not only used for data. Our programs are also stored in files. In order to use files we have to learn about File I/O i.e. how to write information to a file and how to read information from a file. File I/O done by STREAM.

What is Stream ? Stream is not a hardware. It is linear queue which connect file to program and passes block of data in both direction. We can associate a stream with a device (i.e. the terminal) or with a file. We can also define stream as source of data.This source can be A file Hard disk, CD, DVD or I/O devices etc.

Types of Stream C supports two types of Stream – Text Stream – Binary Stream

Text vs Binary How newlines (\n) are stored. How end of file is indicated. How numbers are stored in the file.

System-Created Streams C automatically creates five streams that it opens and closes automatically for us in order to communicate with the terminal: We cannot re-declare these streams in our programs. Standard File PointerDescription Stdin Standard input device(keyborad) StdoutStandard output device(vdu) StderrStandard error device (vdu) Stdaux Standard auxiliary device (serial port) StdpmStandard printing device ( patallel printer)

How to access a File ? A file pointer is needed in order to read or write files. File pointer points to a Structure(FILE)that contains info about the file. FILE structure is declared in stdio.h header file FILE *fp

FILE Structure typedef struct { short level; unsigned flags; char fd; unsigned char hold; short bsize; unsigned char *buffer, *curp; unsigned istemp; short token; } FILE;

File Structure contains info about : Current size of file Location in memory Character pointer points to character to be read

Disk I/O functions Disk I/O Text Formatte d Low LevelHigh Level Binary Formatte d Unformatte d

Opening a File fopen() function opens a stream for use and links a file with that stream. A file pointer associated with that file is then returned by the fopen() function. The prototype for the fopen() is FILE *fopen(const char *filename, const char *mode);

3 Tasks of fopen() File *fp; fp=fopen(“file name”, “mode”); It searches on the disk the file to be opened. If file present then load it from the disk into memory or if file is not present returns a NULL. It sets up a character pointer which points to the first character

More on fopen() The file mode tells C how the program will use the file

File opening Mode Mode Description “r”It opens the file in read mode If file exists,the pointer is positioned at the beginning, else return NULL “w”It opens the file in write mode If file exist, pointer is positioned at the beginning, file overwrite, else create a new file. “a”It opens the file in append mode If file exist, pointer is positioned at the end,if file doesn't exist new file is created.

More on File opening mode

Closing a File When we finish with a mode, we need to close the file before ending the program or beginning another mode with that same file. Closing a stream flushes out any associated buffer, an important operation that prevents loss of data when writing to a disk. int fclose (FILE *fp); The fcloseall() function closes all the open files

Reading a Character The fgetc() function is used for reading character from a file opened in read mode, using fopen(). The prototype for fgetc() is - int fgetc(FILE *fp); If the end of file is reached, fgetc() returns EOF.

Writing a Character Streams can be written to either character by character or as a string The function used for writing characters to a file is fputc(). The prototype for this is - int fputc(int ch, FILE *fp); The fputc() function writes a character to specified stream at the current file position and advances the file pointer.

String I/O The functions fputs() and fgets() are used write and read character strings to and from disk file. The prototypes for the above functions are – int fputs(const char *str, FILE *fp); char *fgets( char *str, int length, FILE *fp); The fputs() function returns EOF if an error occurs. The fgets() function returns a null pointer if an error occurs.

Writing a block of Data Used to read and write an entire block of data to and from a file. Referred to as unformatted read and write functions. The prototypes for these functions are – fread()- size_t fread(void *buffer, size_t num_bytes, size_t count FILE *fp); fwrite()- size_t fwrite(const void *buffer, size_t num_bytes, size_t count FILE *fp);

More on fwrite()/fread() The fread() function returns the number of items read. The fwrite() function returns the number of items written. As long as the file is open for binary operations, fread() and fwrite() can read and write any type of information. One of the most useful applications of fread() and fwrite() is reading and writing user-defined data types like structures.

More on fread() and fwrite() struct emp { char name[40] ; int age ; float bs ; } ; struct emp e ; fwrite ( &e, sizeof ( e ), 1, fp ) Size of the struture in bytes Address of the structure No of structure Pointer to the file

Formatted I/O function fprintf() & fscanf() These functions are similar to printf() and scanf() except that they operate with files. The prototypes of fprintf() and fscanf() are: int fprintf(FILE *fp, const char *control_string, …); int fscanf(FILE *fp, const char *control_string, …);

Current Active pointer In order to keep track of the position where I/O operations Take place a pointer is maintained in the file structure. Whenever a character is read from or written to the stream, The current active pointer is advanced. The current location of the current active pointer can be found with the help of the ftell() function long int ftell( FILE *fp); It returns this position as a long int which is an offset from the beginning of the file

Setting current position We can perform random read and write operations using the C I/O system with the help of fseek( ),which sets the file position indicator The prototype of the fseek() function is – int fseek( FILE *fp, long int offset, int origin);

More on SEEK OriginFile location SEEK_SET or 0Beginning of file SEEK_CUR or 1Current file position pointer SEEK_END or 2End of file

Rewind Function The rewind() function resets the file position indicator to the beginning of the file. The syntax for rewind() is : rewind(fp);

Erasing a File The remove() function erases the specified file. The prototype of the remove() function is – int remove (char *filename); It returns 0 if successful else returns a non zero value

ferror() function The ferror() determines whether a file operation has produced an error. Its prototype is : int ferror(FILE *fp);

Flushing Stream The fflush() function clears the buffer. The action of flushing depends upon the file type. The prototype for this particular function is : int fflush (FLUSH *fp);

More on Flushing Stream The fflush() writes the contents of any buffered data to the file associated with fp. The fflush() function, with a null, flushes all the files opened for output.

Low level Disk I/O Advantages these functions parallel the methods that the OS uses to write to the disk, they are more efficient than the high level disk I/O functions. there are fewer layers of routines to go through, low level I/O functions operate faster than their high level counterparts.

More on Low level I/O There is only one way data can be written or read in low level disk I/O functions as a buffer full of bytes. Declaring the Buffer :- char buffer[512] ; The size of this buffer is important for efficient operation.

What is a Buffer? A buffer is a “special work area” that holds data as the computer transfers them to/from memory. Buffers help to synchronize data the physical devices with the program. The physical requirements of the devices can deliver more data for input than a program can use at any one time. The buffer handles the overflow data until a program can use it. Moreover, the buffer also holds data until it is efficient to write that data to the storage device for output.

Opening a File Mode Description O_APPENDOpens a file for appending O_CREATCreates a new file for writing (has no effect if file already exists) O_RDONLY Creates a new file for reading only O_RDWR Creates a file for both reading and writing O_WRONLYCreates a file for writing only O_BINARYCreates a file in binary mode O_TEXT Creates a file in text mode

cont... file_handler = open(source,opening mode); open( ) returns an integer value called ‘file handle’. This is a number assigned to a particular file, which is used thereafter to refer to the file. If open returns -1 means fine couldn't be successfully opened.

Interaction between Buffer and File bytes = read(file_handler,buffer,256); Read() function returns no of bytes actually read. Write() used for write into the file.