File Handling in C
Outline
• Introduction • Writing into a file
• Writing simple data
• File handling in C • Writing structure data
• File handling commands
• Opening and closing files • Special streams in C
• Stdin, stdout, stderr
• Reading from a file
• Reading simple data • Example
• Reading structure data
What is file?
• A named collection of data, typically stored in a secondary storage (e.g., hard
disk).
Examples
• Records of all employees in an organization
• Document files created using Microsoft Word
• Video of a movie
• Audio of a music
• Non-volatile data storage
• Can be used when power to computer is off
How is a file stored?
• Stored as sequence of bytes, logically contiguous (may not be physically
contiguous on disk).
• Discrete storage unit for data in the form of a stream of bytes.
• Every file is characterized with a starting of file, sequence of bytes
(actual data), and end of stream (or end of file).
• Allow only sequential access of data by a pointer performing.
• Meta-data (information about the file) before the stream of actual data
can be maintained to have a knowledge about the data stored in it.
How is a file stored?
Start EOF
Meta Data 40 65 87 90 24 67 89 90 60 0
File pointer
• The last byte of a file contains the end end-of-file character (EOF, with
ASCII code 1A (Hex).
• While reading a file, the EOF character can be checked to know the
end.
Type of files
• Text files
• Contain ASCII code only
• C-programs
• Binary files
• Contain non-ASCII characters
• Image, audio, video,
executable, etc.
Operations on Files
• Open : To open a file to store/retrieve data
• Read : The file is used as an input
• Write : The file is used as output
• Close : Preserve the file for a later use
• Access: Random accessing data in a file
File Handling Commands
• Include header file <stdio.h> to access all file handling utilities.
• A data type namely FILE is used to create a pointer to a file.
Syntax
FILE * fptr; // fptr is a pointer to file
• To open a file, use fopen() function
Syntax
FILE * fopen(char *filename, char *mode)
• To close a file, use fclose() function
Syntax
int fclose(FILE *fptr);
fopen() function FILE * fopen(char *filename, char *mode)
• The first argument is a string to characters indicating the name of the file to be opened.
Examples:
xyz12.c student.data myFile
• The second argument is to specify the mode of file opening. There are five file opening
modes in C
• "r" : Opens a file for reading
• "w" : Creates a file for writing (overwrite, if it contains data)
• "a" : Opens a file for appending - writing on the end of the file
• “rb” : Read a binary file (read as bytes)
• “wb” : Write into a binary file (overwrite, if it contains data)
• It returns the special value NULL to indicate that it couldn't open the file.
• If a file that does not exist is opened for writing or
appending, it is created as a new.
• Opening an existing file for writing causes the old
fopen() contents to be discarded.
function • Opening an existing file for appending preserves the old
contents, and new contents will be added at the end.
Cont…
• File opening error
• Trying to read a file that does not exist.
• Trying to read a file that doesn’t have permission.
• If there is an error, fopen() returns NULL
fopen() example
#include <stdio.h>
void main()
{
FILE *fptr; // Declare a pointer to a file
char filename[]= "file2.dat";
fptr = fopen(filename,"w"); // alternatively fptr = fopen (“file2.dat”,"w");
if (fptr == NULL) {
printf (“Error in creating file”);
exit(-1); // Quit the function
}
else /* code for doing something */
}
Reading from a file: Simple data
• Following functions in C (defined in stdio.h) are usually used for
reading simple data from a file
• fgetc(…)
• fscanf(…)
• fgets(…)
• getc(…)
Reading from a File: fgetc()
Syntax for fgetc(…)
FILE *fptr;
int fgetc(FILE *fptr)
int c;
/* Open file and check it is open */
• It returns the next character in the stream while ((c = fgetc(fptr)) != NULL)
fptr as an unsigned char (converted to int). {
printf ("%c", c);
• It returns EOF if end of file or error occurs. }
Reading from a File: fscanf()
Syntax for fscanf(…)
int fscanf(FILE *fptr, char *format, ...);
• fscanf reads from the stream fptr under control of format and assigns converted
values through subsequent assignments, each of which must be a pointer.
• It returns when format is exhausted.
• fscanf returns EOF if end of file or an error occurs before any conversion.
• It returns the number of input items converted and assigned.
#include <stdio.h>
int main()
{
FILE* ptr = fopen("abc.txt", "r");
fscanf(): example
if (ptr == NULL) {
printf("no such file."); The %*s ignores the input until the
return 0; next space or newline. Similarly,
} %*d will ignore integers until the
/* Assuming that abc.txt has content in below format next space or newline.
NAME AGE CITY
abc 12 hyderabad
bef 25 delhi
cce 65 bangalore */ Output:
char buf[100]; CITY
while (fscanf(ptr, "%*s %*s %s ", buf) == 1) hyderabad
printf("%s\n", buf); delhi
bangalore
return 0;
}
Reading from a File: fgets(…)
Syntax for fgets(…)
char *fgets(char *s, int n, FILE *fptr)
s The array where the characters that are read will be stored.
n The size of s.
fptr The stream to read.
• fgets() reads at most n-1 characters into the array s, stopping if a newline is encountered.
• The newline is included in the array, which is terminated by ‘\0’.
• The fgets() function returns s or NULL if EOF or error occurs.
fgets() example
FILE *fptr;
char line [1000];
/* Open file and check it is open */
while (fgets(line,1000,fptr) != NULL)
{
printf ("Read line %s\n", line);
}
Reading from a File: getc(…)
Syntax for getc(…)
int getc(FILE *fptr)
• getc(…) is equivalent to fgetc(…) except that it is a macro.
#include <stdio.h>
#include <stdlib.h>
Read a text file and then
int main() print the content on the
{ int ch, fileName[25]; screen
FILE *fp;
printf("Enter the name of file you wish to read\n");
gets(fileName);
fp = fopen(fileName,"r"); // read mode
if( fp == NULL ) Output:
{ printf("Error while opening the file.\n");
Enter the name of file you wish to read
test.txt
exit(-1);}
The contents of test.txt file are :
printf("The contents of %s file are :\n", fileName);
C programming is fun.
while( ( ch = getc(fp) ) != EOF )
printf("%c",ch);
fclose(fp);
return 0;
}
Writing into a file: Simple data
• Following functions in C (defined in stdio.h) are usually used for
writing simple data into a file
• fputc(…)
• fprintf(…)
• fputs(…)
• putc(…)
Writing into a file: fputc(…)
Syntax for fputc(…)
int fputc(int c, FILE *fptr)
• The fputc() function writes the character c to file fptr and returns the
character written, or EOF if an error occurs.
#include <stdio.h>
filecopy(File *fpIn, FILE *fpOut)
{
int c;
while ((c = fgetc(fpIn) != EOF)
fputc(c, fpOut);
}
Writing into a file: fprintf(…)
Syntax for fprintf(…)
int fprintf(FILE *fptr, char *format,...)
• fprintf() converts and writes output to the steam fptr under the control of format.
• The function is like printf() function except the first argument which is a file
pointer that specifies the file to be written.
• The fprintf() returns the number of characters written, or negative if an error
occur.
Writing into a File: fprintf(…)
#include <stdio.h>
void main()
{
FILE *fptr;
fptr = fopen(“test.txt”, “w”);
fprintf(fptr, “Programming in C is really a fun!\n”);
fprintf(fptr, “Let’s enjoy it\n”);
fclose(fptr);
return;
}
Writing into a File: fputs()
Syntax for fputs: #include <stdio.h>
void main()
{
int fputs(char *s, FILE *fptr) FILE *fptr;
fptr = fopen(“test.txt”, “w”);
• The fputs() function writes a string fputs(“Programming in C is really a fun!”,
(which need not contain a newline) fptr);
to a file. fputs(“\n”, fptr);
fputs(“Let’s enjoy it \n”, fptr);
fclose(fptr);
• It returns non-negative, or EOF if an
error occurs. return;
}
Writing into a File: putc(…)
Syntax for putc(…)
#include <stdio.h>
int putc(FILE *fptr) filecopy(File *fpIn, FILE *fpOut)
{
int c;
while ((c = getc(fpIn) != EOF)
putc(c, fpOut);
}
#include <stdio.h> Program to write some text
main()
reading from the keyboard and
{
writing them into a file and
FILE *f1;
char c;
then print the content from the
printf("Data Input\n\n");/* Open the file INPUT */
file on the screen.
f1 = fopen("INPUT", "w");
while((c=getchar()) != EOF) /* Get a character from keyboard*/
putc(c,f1); /* Write a character to INPUT*/
fclose(f1); /* Close the file INPUT*/ Output:
printf("\nData Output\n\n"); Data Input
This is a program to test the file handling
f1 = fopen("INPUT","r"); /* Reopen the file INPUT */ features on this system
while((c=getc(f1)) != EOF) /* Read a character from INPUT*/ Data Output
This is a program to test the file handling
printf("%c",c); /* Display a character on screen */
features on this system
fclose(f1); /* Close the file INPUT */
}
Special streams in C
• When a C program is started, the operating system environment is
responsible for opening three files and providing file pointer for them.
These files are
• stdin Standard input. Normally it is connected to keyboard
• stdout Standard output, In general, it is connected to display screen
• stderr It is also an output stream and usually assigned to a program in
the same way that stdin and stderr are. Output written on
stderr normally appears on the screen
Example: Special Streams
#include <stdio.h>
main()
{ Output:
int i; Give value of i
15
fprintf(stdout,"Give value of i \n"); Value of i=15
fscanf(stdin,"%d",&i);
fprintf(stdout,"Value of i=%d \n",i);
}
Error Handling : stderr and exit
• What happens if the errors are not shown in the screen instead if it's going
into a file or into another program via a pipeline.
• To handle this situation better, a second output stream, called stderr, is
assigned to a program in the same way that stdin and stdout are.
• Output written on stderr normally appears on the screen even if the standard
output is redirected.
Error Handling: Example
#include <stdio.h>
if ((fp = fopen(*++argv, "r")) == NULL) {
main(int argc, char *argv[]) fprintf(stderr, "%s: can't open %s\n", prog,
{ FILE *fp; *argv);
exit(1);
void filecopy(FILE *, FILE *);
} else {
char *prog = argv[0]; /* program name for errors */ filecopy(fp, stdout);
if (argc == 1 ) /* no args; copy standard input */ fclose(fp);}
if (ferror(stdout)) {
filecopy(stdin, stdout);
fprintf(stderr, "%s: error writing stdout\n",
else prog);
while (--argc > 0) exit(2);
}
exit(0);
}
Structured Input/Output for Files
• C language provides the following two functions for storing and retrieving
composite data.
• fwrite() To write a group of structured data
• fread() To read a group of structured data
Writing records: fwrite()
fwrite() writes data from the array pointed to, by ptr to the given stream fptr.
Syntax:
int fwrite(void *ptr, int size, int nobj, FILE *fptr);
• ptr This is the pointer to a block of memory with a minimum size of size
*nobj bytes.
• size This is the size in bytes of each element to be written.
• nobj This is the number of elements, each one with a size of size bytes.
• fptr This is the pointer to a FILE object that specifies an output stream.
#include<stdio.h>
fwrite(&Stu,sizeof(Stu),1,fp);
struct Student
printf("\nDo you want to add another data (y/n) : ");
{
ch = getchar();}
int roll;
while(ch=='y' || ch=='Y');
char name[25];
printf("\nData written successfully...");
float marks;
fclose(fp) }
};
void main()
{ FILE *fp;
int ch;
struct Student Stu; Enter Roll : 1
fp = fopen("Student.dat","w"); //Statement 1 Enter Name : AA
if(fp == NULL) Enter Marks : 78.53
{printf("\nCan't open file or file doesn't exist."); Do you want to add another data (y/n) : y
exit(0); } Enter Roll : 2
do{printf("\nEnter Roll : "); Enter Name : BB
Enter Marks : 72.65
scanf("%d",&Stu.roll); Do you want to add another data (y/n) : y
printf("Enter Name : ");
scanf("%s",Stu.name);
Example: Enter Roll : 3
Enter Name : CC
printf("Enter Marks : "); fwrite() Enter Marks : 82.65
Do you want to add another data (y/n) : n
scanf("%f",&Stu.marks); Data written successfully...
Reading Records: fread()
fread() reads data from the given stream into the array pointed to, by ptr.
Syntax:
int fread(void *ptr, int size, int nobj, FILE *fptr);
• ptr This is the pointer to a block of memory with a minimum size of
size *nobj bytes.
• size This is the size in bytes of each element to be read.
• nobj This is the number of elements, each one with a size of size bytes.
• fptr This is the pointer to a FILE object that specifies an input stream.
#include<stdio.h>
struct Student
{ int roll; Example: fread()
char name[25];
float marks;};
void main()
{ FILE *fp;
int ch;
OUTPUT
struct Student Stu;
fp = fopen("Student.dat","r"); //Statement 1 Roll Name Marks
if(fp == NULL) 1 AA 78.53
{ printf("\nCan't open file or file doesn't exist."); 2 BB 72.65
exit(0);}
3 CC 82.65
printf("\n\tRoll\tName\tMarks\n");
while(fread(&Stu,sizeof(Stu),1,fp)>0)
printf("\n\t%d\t%s\t%f",Stu.roll,Stu.name,Stu.marks);
fclose(fp);}
File handling: Example printf("Enter name of target file\n");
gets(target_file);
#include <stdio.h>
target = fopen(targetFile, "w");
#include <stdlib.h>
int main() if( target == NULL )
{ {
fclose(source);
char ch, sourceFile[20], targetFile[20]; printf(“Output File Error! File copy fails...\n");
FILE *source, *target; exit(-1);
}
printf("Enter name of file to copy\n");
gets(sourceFile); while( (ch = fgetc(source) ) != EOF )
source = fopen(sourceFile, "r"); fputc(ch, target);
if( source == NULL )
printf("File copied successfully.\n");
{
printf(“Input file error. Program abort...\n"); fclose(source);
fclose(target);
exit(-1);
} return 0;
}