FILE IO in ‘C’ by Dr P.Padmanabham Professor (CSE)&Director Bharat Institute of Engineering &Technology Hyderabad Mobile 9866245898

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
Text File Input and Output. Overview Text File Buffered I/O Functions fopen Function Demo of File Write and Read.
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.
Chapter 11 C File Processing Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education Inc.
CS1061: C Programming Lecture 19: Random Access Files A. O’Riordan, 2004, 2007 updated.
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.
 Types of files  Command line arguments  File input and output functions  Binary files  Random access.
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.
N305: C Programming Copyright ©2006  Department of Computer & Information Science File Handling in C.
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.
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.
File IO and command line input CSE 2451 Rong Shi.
Chapter 8 File-Oriented Input and Output. 8.1 INTRODUCTION a file can also be designed to store data. We can easily update files, A data file as input.
Digital Computer Concept and Practice Copyright ©2012 by Jaejin Lee C Language Part 4.
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.
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 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.
C Program Design C File Processing 主講人:虞台文. Content Introduction Data Hierarchy Files and Streams Creating a Sequential-Access File Reading Data from.
CNG 140 C Programming (Lecture set 10) Spring Chapter 10 Data Files.
C Programming Lecture 12 : File Processing
C File Processing. Objectives To be able to create, write and update files. To become familiar with sequential access file processing. To become familiar.
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()”
Adv. UNIX:fp/101 Advanced UNIX v Objectives of these slides: –a more detailed look at file processing in C Special Topics in Comp. Eng.
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.
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.
 2007 Pearson Education, Inc. All rights reserved C File Processing.
Lecture 12 CIS 208 Friday, March 3rd , 2005.
Chapter 4 File Processing
Chapter 9 – File Input Output
Lecture 11 File input/output
TMF1414 Introduction to Programming
Introduction to Computer Programming Lecture 18 Binary Files
File I/O.
Session #5 File I/O Bit Masks, Fields & Bit Manipulations
CSC215 Lecture Input and Output.
CS111 Computer Programming
What you need for the 1st phase of project
Introduction to Programming
Introduction to Programming
File I/O We are used to reading from and writing to the terminal:
Chapter 11 – File Processing
Lecture 15 Files.
CSC215 Lecture Input and Output.
CSC215 Lecture Input and Output.
Beginning C Lecture 11 Lecturer: Dr. Zhao Qinpei
Text and Binary File Processing
Henning Schulzrinne Columbia University
Fundamental of Programming (C)
C Input / Output Prabhat Kumar Padhy
Chapter 12: File I/O.
FILE handeling.
CSc 352 File I/O Saumya Debray Dept. of Computer Science
Professor Jodi Neely-Ritz University of Florida
I/O CS580U - Fall 2018.
File I/O We are used to reading from and writing to the terminal:
Presentation transcript:

FILE IO in ‘C’ by Dr P.Padmanabham Professor (CSE)&Director Bharat Institute of Engineering &Technology Hyderabad Mobile

Topics Coverd Introduction to Files Text files- character IO Data Text files –Formatted IO Variable Argument Functions Handling Binary data files Random access of files Error handling in File IO Some basic ideas of Low level IO

Text and Binary Files A file is stream of bytes. A file is also referred as stream. Most people classify files in two categories: binary files and ASCII (text) files At heart all files are binary files -- that is, a collection of 1s and 0s. But there is a subset of binary files we call ASCII, or plain text files, where all the bytes stored are in ASCII

Text and binary files contd. Since a text file holds printable characters (ASCII) it can be edited by a text editor. Examples of Text files- program source files and some data files. A binary file is one that holds information in bytes that may not be printable or editable. Examples of binary files-obj, exe files and some data files.

File Pointer FILE *fp; FILE is a structure difined in stdio.h. FILE *fopen(const char *filename, const char *mode); To open a file you need to use the fopen function, which returns a FILE pointer on success and NULL on failure. Once you've opened a file successfully, you can use the FILE pointer to perform input and output functions on the file. To close a file you need to use int fclose(FILE *fp);

Text-file Modes r - open for reading (file must exist) w - open for writing (file overwritten if exists) a - open for appending (file need not exist) r+ - open for reading and writing, start at beginning (file must exist) w+ - open for reading and writing (overwrite file) a+ - open for reading and writing (app end if file exists ) Note:- add b to above for binary files

Example of Opening & Closing a File The following segment of code illustrates opening and closing a file FILE *fp; If((fp=fopen(“test.txt", "r"))==NULL) { printf(“File:could not be opend\n”); exit(1); } fclose(fp);

Character I/O on text files int fgetc (FILE *fp); Int fputc(int c,FILE *fp); The fgetc function allows you to read a character at a time The fputc function allows you to write a character at a tim e

Write to text file from key board #include void main() { FILE *fp; char c; fp=fopen("my1.dat",“w"); while((c=fgetc(stdin))!=EOF)fputc(c,fp); fclose(fp);/* EOF is ctl z in DOS and ctl d in unix*/ }

Count words and lines in a text file #include void main(int argc,char *argv[]) { FILE *fp; int wc=0,lc=0; char c; if(argc!=2) {printf(“Error..File name required\n); exit(1);} fp=fopen(argv[1],"r");

while((c=fgetc(fp))!=EOF) { if(c==' ')wc++; If(c=='\n') { wc++; lc++; while((c=fgetc(fp))==' '); } printf("WC=%d\tLC=%d\n",wc,lc); fclose(fp); }

Using formated I/o on text files int fprintf(FILE *fp,char *fmt,…) int fscanf(FILE *fp,char *fmt,…) For example the following code writes one integer and one float into the file using fprintf and reads back using fscanf fprintf(fp, “%d \t % f \n“, i, f); /* you have to position the file back to read what is written*/ fscanf(fp, “%d % f “, &i, &f);

Binary data files Data can be stored either in text mode(previous section) or in binary mode. In text data files, data needs to be converted back and forth from binary to ASCII while writing and reading where as in binary mode directly the memory image can be stored and retrieved. Another incidental advantage of binary data files as against text data files is that they cannot be edited by a text editor and therefore cannot be tampered easily. Binary files occupy less space. Imagine 1 million records stored in a database.

Binary data file IO-fread() int fread( void *buffer, size_t size, size_t num, FILE *stream ); The function fread() reads num number of objects (where each object is size bytes) from the stream and places them into the memory pointed to by buffer. The return value of the function is the number of things(objects) read and 0 when eof is encountered

Binary data file IO- fwrite() int fwrite( const void *buffer, size_t size, size_t count, FILE *stream ); The fwrite() function writes, from the memory pointed by buffer, count number of objects of size size to stream. The return value is the number of objects written.

Binary file IO #include void main(int argc,char*argv[]){ FILE *fp; int i,n; struct { char name[30]; int empno; float sal; } emp;

if(argc!=2) { printf("Error...file name not given\n"); exit(1); } fp=fopen(argv[1],"wb"); for(i=0;i<3;i++) { fflush(stdin); printf("enter Name:"); gets(emp.name);

printf("enter empno:"); scanf("%d",&emp.empno); printf("enter Sal:"); scanf("%f",&emp.sal); n=fwrite(&emp,sizeof(emp),1,fp); printf("%d \n",n); } fp=freopen(argv[1],"rb",fp); while((fread(&emp,sizeof(emp),1,fp))) { printf("Name:%s\n",emp.name);

printf("Empno:%5d\n",emp.empno); printf("Salary:%8.2f\n",emp.sal); } fclose(fp); }

Random access of file fseek() function sets the file position indicator for the stream pointed to by the FILE pointer to a position you seeks within a file and modify it. Its syntax is: fseek(FILE *stream, long int offset, int whence) The value of whence must be one of the constants SEEK_SET, SEEK_CUR, or SEEK_END, to indicate whether the offset is relative to the beginning of the file, the current file position, or the end of the file, respectively.

fell() and rewind() The ftell function obtains the current value of the file position indicator for the stream pointed to by stream. Syntax long ftell(FILE *stream) The rewind function sets the file position indicator for the stream pointed to by stream to the beginning of the file. It is equivalent to: fseek(stream, 0L, SEEK_SET) Sntax: void rewind(FILE* stream)

Example of random access #include void main(){ FILE *fp; int i,n; struct{ char name[30]; int empno; float sal; } emp; long rpos,f_size; rpos=41L; fp=fopen("temp.dat","r+");

fseek(fp,0,SEEK_END); if(fgetc(fp)==EOF){ f_size=ftell(fp); printf("File Size:%d\n",f_size); } while(1){ printf("which record?\n"); scanf("%d",&n); if(n<0)break; if(rpos*(n-1)>=f_size-1){printf("NO Record\n");continue;} if(fseek(fp,rpos*(n-1),SEEK_SET)){ printf("ERROR!!!\n");continue;}

fscanf(fp,"%s %d %f", emp.name,&emp.empno,&emp.sal); printf("Name:%s\n",emp.name); printf("Empno:%5d\n",emp.empno); printf("Salary:%8.2f\n",emp.sal); emp.sal=25000; fseek(fp,rpos*(n-1),SEEK_SET); fprintf(fp1,"%25s\t%5d\t%10.2f\n", emp.name,emp.empno,emp.sal); } fclose(fp); }

Error Handling Functions The clearerr function void clearerr(FILE *stream); The clearerr function clears the end-of-file and error indicators for the stream pointed to by stream The feof function int feof(FILE *stream); The feof function tests the end-of-file indicator for the stream pointed to by stream and returns nonzero if and only if the end-of-file indicator is set for stream, otherwise it returns zero.

Error handling contd… The ferror function int ferror(FILE *stream); The ferror function tests the error indicator for the stream pointed to by stream and returns nonzero if and only if the error indicator is set for stream, otherwise it returns zero. The perrorr function void perror(const char *s); The perror function maps the error number in the integer expression errno to an error message. It writes a sequence of characters to the standard error stream,the string pointed to by s followed by a colon (:) and a space; then an appropriate error message string.