14 File Handling in C
14 File Handling in C
What is a 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
Start EOF
Meta Data 40 65 87 90 24 67 89 90 60 0
File pointer
Note:
• 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.
*Program-cosole and File Interaction
Streams
*All input and output is performed with streams.
*A "stream" is a sequence of characters organized
into lines.
*Each line consists of zero or more characters and
ends with the "newline" character.
Types of Streams
in C
*Standard input stream is called "stdin" and is
normally connected to the keyboard
*Standard output stream is called "stdout" and is
normally connected to the display screen.
*Standard error stream is called "stderr" and is also
normally connected to the screen.
Type of Files
• Text files
– Contain ASCII code only
• C-programs
• Binary files
– A binary file contains data in binary form (i.e. 0’s and 1’s) instead of ASCII characters.
– They contain data that is stored in a similar manner to how it is stored in the main memory.
• The binary files can be created only from within a program and their contents can only be read by a
program.
• More secure as they are not easily readable.
• They are generally stored with .bin file extension.
File Handling in C
Operations on Files
• Typical operations on a file are
• Naming : Naming of file
#include <stdio.h>
int main()
{
char name[50];
int marks, i, num;
FILE *fptr;
fptr = (fopen("C:\\student.txt", "w"));
if(fptr == NULL)
{
printf("Error!");
exit(1);
}
fclose(fptr);
return 0;
}
*I l ncl ~dt !< stdio.h > ' I i,nc'!Lude <
conio.h > '· · • Voi(j main( )
Examples:
xyz12.c student.data File PDS.txt
myFile
• "a" : Opens a file for appending - writing on the end of the file
• fscanf(…)
• fgets(…)
• getc(…)
• ungetc(…)
• The fgetc() function returns the next character in the stream fptr as an
unsigned char (converted to int).
FILE *fptr;
int c;
/* Open file and check it is open */
while ((c = fgetc(fptr)) != NULL)
{
printf ("%c",c);
}
• 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.
n = fscanf(fptr,“%d %d”,&x,&y);
x = 20
x = 30
...
FILE *fptr;
char line [1000];
/* Open file and check it is open */
if( fp == NULL )
{
printf("Error while opening the file.\n");
exit(-1);
}
OUTPUT
printf("The contents of %s file are :\n", fileName);
while( ( ch = getc(fp) ) != EOF )
Enter the name of file you wish to read
printf("%c",ch);
test.txt
fclose(fp); The contents of test.txt file are :
return 0; C programming is fun.
}
#include <stdio.h>
int main(void)
{ OUTPUT
int ch;
a
while ((ch = getchar()) != '1') // reads characters from the stdin a
putchar(ch); // and show them on stdout until encounters
v '1'
v
ungetc(ch, stdin); // ungetc() returns '1' previously read back to stdin
c
c
ch = getchar(); // getchar() attempts to read next character from stdin
u
// and reads character '1' returned back to the stdin by ungetc()
u
putchar(ch); // putchar() displays character 1
puts(""); 1
Thank you!
printf("Thank you!\n");
return 0;
}
• fprintf(…)
• fputs(…)
• putc(…)
• The fputc() function writes the character c to file fptr and returns the
character#include <stdio.h>
written, or EOF if an error occurs.
{
int c;
void main()
{
FILE *fptr;
fptr = fopen(“test.txt”, “w”);
fclose(fptr);
return;
}
• The fputs() function writes a string (which need not contain a newline) to
a file.
void main()
{
FILE *fptr;
fptr = fopen(“test.txt”, “w”);
fclose(fptr);
return;
}
{
int c;
main()
{
FILE *f1;
char c;
printf("Data Input\n\n");
/* Open the file INPUT */
Contd…
f1 = fopen("INPUT", "w");
CS 10001 : Programming and Data Stru 45 Lecture #07: © DSamanta
ctures
Writing into a File
while((c=getchar()) != EOF) /* Get a character from keyboard*/
OUTPUT
putc(c,f1); /* Write a character to INPUT*/
Data Input
Note:
getc(stdin) is same as fgetc (stdin)
CS 10001 : Programming and Data Stru 48 Lecture #07: © DSamanta
ctures
Special Streams
printf(“"Hello World!\n");
OUTPUT
Give value of i
15
Value of i=15
#include <stdio.h>
Contd…
CS 10001 : Programming and Data Stru 52 Lecture #07: © DSamanta
ctures
Example: Error Handling
if (ferror(stdout)) {
fprintf(stderr, "%s: error writing stdout\n", prog);
exit(2);
}
exit(0);
}
struct Student
{
int roll;
char name[25];
float marks;
};
void main()
{
FILE *fp;
int ch;
struct Student Stu;
fp = fopen("Student.dat","w"); //Statement 1
if(fp == NULL)
{
printf("\nCan't open file or file doesn't exist.");
exit(0);
}
Contd…
CS 10001 : Programming and Data Stru 57 Lecture #07: © DSamanta
ctures
Example: fwrite()
do
{
printf("\nEnter Roll : ");
scanf("%d",&Stu.roll);
fwrite(&Stu,sizeof(Stu),1,fp);
}while(ch=='y' || ch=='Y');
fclose(fp);
}
Contd…
CS 10001 : Programming and Data Stru 58 Lecture #07: © DSamanta
ctures
Example: fwrite()
OUTPUT
Enter Roll : 1
Enter Name : AA
Enter Marks : 78.53
Do you want to add another data (y/n) : y
Enter Roll : 2
Enter Name : BB
Enter Marks : 72.65
Do you want to add another data (y/n) : y
Enter Roll : 3
Enter Name : CC
Enter Marks : 82.65
Do you want to add another data (y/n) : n
struct Student
{
int roll;
char name[25];
float marks;
};
void main()
{
FILE *fp;
int ch;
struct Student Stu;
fp = fopen("Student.dat","r"); //Statement 1
if(fp == NULL)
{
printf("\nCan't open file or file doesn't exist.");
exit(0);
}
Contd…
CS 10001 : Programming and Data Stru 61 Lecture #07: © DSamanta
ctures
Example: fread()
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);
}
OUTPUT
Example
long n;
n = ftell(fptr);
Note:
In this case, n gives the relative offset (in bytes) of the current position. This
means that n bytes have already been read (or written).
CS 10001 : Programming and Data Stru 65 Lecture #07: © DSamanta
ctures
Random Accessing a File: fseek()
int fseek(FILE *fptr, long offset, int whence);
Example
rewind (fptr); // Set the file pointer at the beginning
fseek(fptr, 0L, SEEK_SET); // same as the rewind()
int main()
{
char ch, sourceFile[20], targetFile[20];
FILE *source, *target;
fclose(source);
fclose(target);
return 0;
}
CS 10001 : Programming and Data Stru 72 Lecture #07: © DSamanta
ctures
File Handling : Example 2
A program to copy a text file to another file. Read the file names through command line.
#include <stdio.h>
#include <stdlib.h>
fclose(source);
fclose(target);
return 0;
}
#include <stdio.h>
#include <stdlib.h>
fclose(fpA);
fclose(fpB);
return 0;
}
#include <stdio.h>
#include <stdlib.h>
fclose(source);
fclose(target);
return 0;
}
fclose(source);
return 0;
}
CS 10001 : Programming and Data Stru 79 Lecture #07: © DSamanta
ctures
File Handling : Example 6
A program to store a record in file. Read the file and store all records in an array.
#include <stdio.h>
#include <stdlib.h>
struct Student {
int rollNo;
char name[20];
float marks;
};
while (choice) {
data = (struct *)malloc(sizeof(struct Student));
if (data != NULL) {
printf(\nEnter Roll No: “); scanf(“%d”,&data->rollNo;);
printf(\nEnter Name: “); scanf(“%s”,data->name;);
fclose(outfile);
return 0;
}
return 0;
}