PPS Chapter Files
PPS Chapter Files
Files: Introduction to files, file operations, reading data from files, writing data to files, error handing
during file operations.
Preprocessor Directives: Types of preprocessor directives
File Handling
INTRODUCTION :
In real world application when data is large then it is necessary to stored on the disk in files. A file
represents a sequence of bytes. file is created in secondary storage. Files are of two types text file and
binary file.
C language provides access on files with high/low level functions .FILE is a structure defined in
standard input/output library. file pointer is created and used as
Text File : A text stream consist of a sequence of characters. they are grouped in line. stores the data in
the text form
Binary File : stores the data in the binary form (1's and 0's). a binary stream consist of a sequence of
data. they stored in their memory representation.
creating a file
opening a file
writing into the file
reading from the file
close the file
Operations Description
fopen() create a file or open an existing file
fclose() close a file
getc() read a character
putc() write a character
fprintf() write a formatted values
fscanf() read set of values
getw() read an integer
putw() write an integer
After performing all operation on the file must be closed at the end
fclose()is used for closing the file
The fclose() function returns zero on success, or EOF if there is an error in closing the file
FILE *fp; // file pointer
fclose(fp); // at the end close the file
FILE *fp;
fp = fopen(“abc.txt”,”r”);
fclose(fp);
INPUT/OUTPUT OPERATIONS ON FILES
fputc() is used to write a character ch in the file pointed by fp. it returns the character on success
otherwise EOF.
fputs(char *s,FILE *fp) is used to write a string into the file. it returns the negative value on success
otherwise EOF.
fprintf(FILE *fp ,"format ",...) is similar to printf function but it prints the formated data into the file
Syntax :
putw() is used for writing a integer to a file
Syntax :
fwrite(void *p, int size, int no, FILE *fp) writes a block of data into the file reading from the file
Syntax :
int fgetc(FILE *fp) is used to read a charecter from the file otherwise EOF on end of the file
Syntax :
char *fgets(char *str, int n,FILE *fp) is used to read a string from the file
Syntax :
fscanf(FILE *fp,"format", ..) it is similar to scanf function but it is used to read from the file
Syntax :
getw() to read a integer from a file
Syntax :
fread(void *ptr, int size,int no,FILE *fp) reads a block of data from the file
Syntax :
#include <stdio.h>
int main() {
int i;
FILE * fptr;
char fn[50];
fputc(str[i], fptr);
fclose(fptr);
return 0;
fscanf(fptr,"%d", &num);
return 0;
. }
RANDOM ACCESS FILE OPERATION
ferror() it is used to check the error status of the file. it returns true if it finds error, otherwise false.
clearerr() this function is used to change the status of the file from error
syntax: void clearerr(FILE *fp);
Pre-processor Commands: