FILE HANDLING IN C.

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

Using Files Declare a variable, called file pointer, of type FILE * Use function fopen to open a named file and associate this file with the file pointer.
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.
Chapter 11: Data Files & File Processing In this chapter, you will learn about Files and streams Creating a sequential access file Reading data from a.
C Programming - Lecture 3 File handling in C - opening and closing. Reading from and writing to files. Special file streams stdin, stdout & stderr. How.
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.
© Janice Regan, CMPT 128, Jan CMPT 128: Introduction to Computing Science for Engineering Students C File Input and Output Checking input for errors.
C Basic File Input/Output Manipulation C Programming – File Outline v File handling in C - opening and closing. v Reading from and writing to 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.
File Handling Spring 2013Programming and Data Structure1.
Engineering H192 - Computer Programming The Ohio State University Gateway Engineering Education Coalition Lect 7P. 1Winter Quarter File I/O in C Lecture.
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. Introduction File Declaration and Initialization Creating and Opening File Closing File EOF Reading from and Writing into a File Extra : Random Access.
Introduction to Programming Using C Files. 2 Contents Files Working with files Sequential files Records.
CSEB114: Principle of programming Chapter 11: Data Files & File Processing.
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:
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.
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.
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)
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()”
1 CSC103: Introduction to Computer and Programming Lecture No 27.
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.
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.
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.
TMF1414 Introduction to Programming
EKT120: Computer Programming
File I/O.
File Handling in C.
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
CSE1320 Files in C Dr. Sajib Datta
What you need for the 1st phase of project
File Handling in C.
FILE HANDLING.
Files I/O, Streams, I/O Redirection, Reading with fscanf
CSE1320 Files in C Dr. Sajib Datta
Chapter 11 – File Processing
CSE1320 Strings Dr. Sajib Datta
IPC144 Week 10 – Lesson 2 Working with Files
File I/O in C Lecture 7 Narrator: Lecture 7: File I/O in C.
Programming and Data Structure
File Input and Output.
File Handling.
File Handling in C.
Fundamental of Programming (C)
File Handling in C.
EPSII 59:006 Spring 2004.
FILE handeling.
ETE 132 Lecture 8 By Munirul Haque.
C Programming - Lecture 3
CSc 352 File I/O Saumya Debray Dept. of Computer Science
Course Contents KIIT UNIVERSITY Sr # Major and Detailed Coverage Area
Professor Jodi Neely-Ritz University of Florida
Files Chapter 8.
Presentation transcript:

FILE HANDLING IN C

Files in C In C, each file is simply a sequential stream of bytes. C imposes no structure on a file. A file must first be opened properly before it can be accessed for reading or writing. When a file is opened, a stream is associated with the file. Successfully opening a file returns a pointer to (i.e., the address of) a file structure, which contains a file descriptor and a file control block. 12/28/2018 2

File Operations Creation of new file Opening of existing file Reading from file Writing to file Moving to specific location in a file Closing a file

Files in C The statement: FILE *fptr1, *fptr2 ; declares that fptr1 and fptr2 are pointer variables of type FILE. They will be assigned the address of a file descriptor, that is, an area of memory that will be associated with an input or output stream. Whenever you are to read from or write to the file, you must first open the file and assign the address of its file descriptor (or structure) to the file pointer variable. 12/28/2018 4

Opening Files The statement: fptr1 = fopen ( "mydata", "r" ) ;  would open the file mydata for input (reading). fptr2 = fopen ("results", "w" ) ;  would open the file results for output (writing). Once the files are open, they stay open until you close them or end the program (which will close all files.) 12/28/2018 5

Modes for opening files The second argument of fopen is the mode in which we open the file. There are three "r" opens a file for reading "w" opens a file for writing - and writes over all previous contents (deletes the file so be careful!) "a" searches a file for appending - writing on the end of the file. 12/28/2018 6

The exit() function Sometimes error checking means we want an "emergency exit" from a program. We want it to stop dead. In main we can use "return" to stop. In functions we can use exit to do this. Exit is part of the stdlib.h library exit(-1); in a function is exactly the same as return -1; in the main routine 12/28/2018 7

Testing for Successful Open If the file was not able to be opened, then the value returned by the fopen routine is NULL. For example, let's assume that the file mydata does not exist. Then: FILE *fptr1 ; fptr1 = fopen ( "mydata", "r") ; if (fptr1 == NULL) { printf ("File 'mydata' did not open.\n") ; } 12/28/2018 8

Reading From Files In the following segment of C language code: int a, b ; FILE *fptr1, *fptr2 ; fptr1 = fopen ( "mydata", "r" ) ; fscanf ( fptr1, "%d%d", &a, &b) ; the fscanf function would read values from the file "pointed" to by fptr1 and assign those values to a and b. 12/28/2018 9

End of File The end-of-file indicator informs the program when there are no more data (no more bytes) to be processed. There are a number of ways to test for the end-of-file condition. One is to use the feof function which returns a true or false condition: fscanf (fptr1, "%d", &var) ; if ( feof (fptr1) ) { printf ("End-of-file encountered.\n”); } 12/28/2018 10

End of File There are a number of ways to test for the end-of-file condition. Another way is to use the value returned by the fscanf function: int istatus ; istatus = fscanf (fptr1, "%d", &var) ; if ( istatus == EOF ) { printf ("End-of-file encountered.\n”) ; } 12/28/2018 11

Writing To Files Likewise in a similar way, in the following segment of C language code: int a = 5, b = 20 ; FILE *fptr2 ; fptr2 = fopen ( "results", "w" ) ; fprintf ( fptr2, "%d %d\n", a, b ) ; the fprintf functions would write the values stored in a and b to the file "pointed" to by fptr2. 12/28/2018 12

Closing Files The statements: fclose ( fptr1 ) ; fclose ( fptr2 ) ;   will close the files and release the file descriptor space and I/O buffer memory. 12/28/2018 13

/* display contents of file on screen.*/ #include<stdio.h> Void main() { FILE *fp; char ch; fp=fopen(“pri.c”,”r”); While(1) ch=fgetc(fp); If(ch==EOF) break; printf(“%c”,ch); } fclose(fp);

Explanation: fopen() does 3 jobs namely 1) it searches on disk the file to be opened. 2) then it loads file from disk into memory called buffer. 3) it sets up character pointer that points to 1st character of the buffer. fgetc() reads chracter from current pointer position, advances pointer so that it points to next character. It gets stored in variable “ch”. fclose(fp) buffer associated with file is removed from memory. fputc() writes character to buffer.

/* count chars,spaces,tabs and newlines in a file*/ #include<stdio.h> Void main() { FILE *fp; char ch; int nol=1;not=0,nob=0,noc=0; fp=fopen(“pri.c”,”r”); while(1) ch=fgetc(fp); if(ch==EOF) break; noc++; if(ch==‘ ‘) nob++;

if(ch==‘\n’) nol++; if (ch==‘\t’) not++; } fclose(fp); printf(“\n number of characters=%d”,noc); printf(“\n number of blanks=%d”,nob); printf(“\n number of tabs=%d”, not); printf(“\n number of lines=%d”,nol); getch();

Program takes contents of a file and copies them into another file, character by character. #include<stdio.h> #include<stdlib.h> Void main() { FILE *fs, *ft; char ch; fs=fopen(“pr1.c”,”r”); if(fs==NULL) puts(“cannot open source file”); exit(1); } ft=fopen(“pr2.c”,”w”); if(ft==NULL) puts(“cannot open target file”);

fclose(fs); exit(2); } While(1) { ch=fgetc(fs); if(ch==EOF) break; else fputc(ch,ft); fclose(ft);

/* Receives strings from keyboard and writes them to file*/ #include<stdio.h> #include<stdlib.h> #include<string.h> void main() { FILe *fp; char s[80]; fp=fopen(“poem.txt”,”w”); if(fp==NULL) puts(“cannot open file”); exit(1); } printf(“\n enter a few lines of text:\n”);

while(strlen(gets(s))>0) { fputs(s,fp); fputs(“\n”,fp); } fclose(fp);

Note that each string is terminated by hitting “enter”. Explanation: Note that each string is terminated by hitting “enter”. To terminate the execution of program, hit “enter” at the beginning of a line- signal to close file. fputs() writes contents of array to disk. It doesn’t automatically add a newline character to end of the string, we must do explicitly .

/* write records to a file using structure*/ #include<stdio.h> #incude<conio.h> Void main() { FILE *fp; char another=‘y’; struct emp char name[40]; int age; float bs; }; Struct emp e; fp=fopen(“employee.dat”,”w”); If(fp==NULL)

puts(“cannot open file”); exit(1); } while (another==‘y’) { printf(“\n enter name,age and basic salary:”); scanf(“%s%d%f”, &e.name,&e.age,&e.bs); fprintf(fp,”%s%d%f\n”,e.name,e.age,e.bs); printf(“add another record(y/n)”); fflush(stdin); another=getch(); fclose(fp);

fprintf() writes values in structure variable to the file. Explantion: we are reading data into structure variable using scanf(), and then dumping it into disk file using fprintf(). fprintf() writes values in structure variable to the file. fflush() removes any data remaining in the buffer. Stdin buffer related with standard input device- keyboard.