0% found this document useful (0 votes)
80 views10 pages

File Handling

The document discusses file handling in C programming. It defines streams as the input/output channels used for file handling. There are two categories of streams: text streams and binary streams. Text streams handle characters while binary streams can handle any data type. The document outlines functions for opening, closing, reading from, and writing to both text files and binary files.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
80 views10 pages

File Handling

The document discusses file handling in C programming. It defines streams as the input/output channels used for file handling. There are two categories of streams: text streams and binary streams. Text streams handle characters while binary streams can handle any data type. The document outlines functions for opening, closing, reading from, and writing to both text files and binary files.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

C Programming Language File Handling

Agenda:
 What is a Stream
 Opening and Closing of Files
 Writing and Reading in Text Format
 Writing and Reading in Binary Format

What is Stream

Categories of Streams:
 Character / Text Stream
 Binary Stream

Text Streams
In a stream of text, one unit of data is one character i.e. at a time we read or write a character or an array of
characters. Here we should know the type of encoding before we can read characters from text stream. Based on
the type of encoding used number of bytes a character takes is decided and this remains fixed throughout the
stream.
S A N D E E P
01010011 01000001 01001110 01000100 01000101 01000101 01010000

Binary Streams
In a stream of Binary, the unit of data is not fixed as it can be of any date type. The order of writing to the stream
must be known so that in the same order we can read data from the stream.
Short(2) Integer(4) Float(4) char(1) Char(1)
10101000111010101 10100110101010101010011010101010 10100110101010101010011010101010 01000110 1010011

Files allows us to store information permanently and access, alter that information whenever necessary
C Programming Language File Handling

Opening and Closing a File


Opening Files
FILE * fopen(const char * filename, const char * mode );
It creates a new file or to open an existing file and returns the pointer to the same. The returned pointer can be
used for writing to the file or reading from the file.

Following are the access mode used for text files:

Mode Description

r Opens an existing text file for reading purpose.

Opens a text file for writing, if it does not exist then a new file is created. Here your program will start
w
writing content from the beginning of the file.

Opens a text file for writing in appending mode, if it does not exist then a new file is created. Here your
a
program will start appending content in the existing file content.

r+ Opens a text file for reading and writing both.

Opens a text file for reading and writing both. It first truncate the file to zero length if it exists otherwise
w+
create the file if it does not exist.

Opens a text file for reading and writing both. It creates the file if it does not exist. The reading will start
a+
from the beginning but writing can only be appended.

For Binary Files following access modes must be used


"rb", "wb", "ab", "rb+", "r+b", "wb+", "w+b", "ab+", "a+b"

Closing a File
int fclose( FILE *fp );
The fclose( ) function returns zero on success, or EOF if there is an error in closing the file
This function actually, flushes any data still pending in the buffer to the file, closes the file, and releases any
memory used for the file.
C Programming Language File Handling

Writing and Reading in Text Format


Writing to a Text File
To write individual characters to a stream
int fputc( int c, FILE *fp );
It returns the written character written on success otherwise EOF if there is an error

To write a null-terminated string to a stream:


int fputs( const char *s, FILE *fp );
int fprintf(FILE *fp, const char *format, ...)
Both returs a non-negative value on success, otherwise EOF is returned in case of any error.
int fprintf(FILE *fp, const char *format, ...)

Reading from a Text File


To read a single character from a file

int fgetc( FILE * fp );


The return value is the character read, or in case of any error it returns EOF

To Read a string from file


char *fgets( char *buf, int n, FILE *fp );
The functions fgets() reads up to n - 1 characters from the input stream referenced by fp. It copies the read string
into the buffer buf, appending a null character to terminate the string.

Note: You can also use int fscanf(FILE *fp, const char *format, ...) function to read strings from a file but it stops
reading after the first space character encounters.

//To Read from a Text File

int main()

FILE *file = fopen("d:\\demo.txt","r");

if (file == NULL)

printf("Error opening a file...");

return 1;
C Programming Language File Handling
}

while(1)

int ch = fgetc(file);

if (ch == EOF)

break;

printf("%c",ch);

fclose(file);

return 0;

//To Write to a Text File

int main()

FILE *file = fopen("d:\\demo.txt","w");

if (file == NULL)

printf("Error opening a file...");

return 1;

while(1)

char ch = getchar();

if (ch == EOF)

break;

putc(ch,file);

}
C Programming Language File Handling
fclose(file);

return 0;

Example for Writing and Reading Structure in Text Format

//Writing Structure data to a Text File

struct Student

int RollNo;

char Name[30];

double Marks;

};

int main()

struct Student s1,s2;

FILE *file = fopen("d:\\student.txt","w+");

if (file == NULL)

printf("Error in saving student data");

return 1;

while(1)

printf("Enter RollNo: ");

scanf("%d",&s1.RollNo);

printf("Enter Name: ");

scanf("%s",&s1.Name);

printf("Enter Marks: ");


C Programming Language File Handling

scanf("%lf",&s1.Marks);

fprintf(file,"%d\t%s\t%lf\n",s1.RollNo,s1.Name,s1.Marks);

printf("Continue (Y/N)");

char ch = getch();

if (ch == 'N' || ch == 'n')

break;

fclose(file);

return 0;

//Reading Structure data from a Text File

int main()

struct Student s1,s2;

FILE *file = fopen("d:\\student.txt","r");

if (file == NULL)

printf("Error in reading student data");

return 1;

while(1)

int cnt=fscanf(file,"%d\t%s\t%lf\n",&s1.RollNo,&s1.Name,&s1.Marks);

if (cnt == -1)

break;

printf("\n%d\t%s\t%lf\n",s1.RollNo,s1.Name,s1.Marks);
C Programming Language File Handling

fclose(file);

return 0;

Writing and Reading in Binary Format

Following are the Methods used for Reading and Writing in Binary Format:

 size_t fread(void *data, size_t size_of_element, size_t number_of_elements, FILE *a_file);

 size_t fwrite(const void *data, size_t size_of_element, size_t number_of_elements, FILE *a_file);

 fseek(FILE *a_file,size_t offset, size_t position);


Allows moving file –pointer forward /backward
<Offset>: is the number of bytes we want ti move from the current position in the file, which is indicated
by the file pointer and can be –ve or +ve
<Position>: Indicates the location in the file from where one wishes to move .it can be any of the
fallowing values
 0: movement from beginning of the file
 1: movement from the current position in the file
 2: movement from the end of the file

 long ftell(FILE * a_file) returns the current file position in the file returns a long value
long position = ftell(fp);

Program to Write Student data in Binary Format

struct Student
{
int RollNo;
char Name[30];
double Marks;
};
C Programming Language File Handling

int main()
{
struct Student s1,s2;
FILE *file = fopen("d:\\student.dat","w+b");
if (file == NULL)
{
printf("Error in saving student data");
return 1;
}
while(1)
{
printf("Enter RollNo: ");
scanf("%d",&s1.RollNo);
printf("Enter Name: ");
scanf("%s",&s1.Name);
printf("Enter Marks: ");
scanf("%lf",&s1.Marks);

//fprintf(file,"%d\t%s\t%lf\n",s1.RollNo,s1.Name,s1.Marks);
fwrite(&s1,sizeof(s1),1,file);

printf("Continue (Y/N)");
fflush(stdin);
char ch = getchar();
if (ch == 'N' || ch == 'n')
break;
}
fseek(file,0,0);
while(1)
{
int n = fread(&s2,sizeof(s2),1,file);
if (n == 0)
break;
printf("%d %s %lf\n",s2.RollNo,s2.Name,s2.Marks);
}
fclose(file);
C Programming Language File Handling

return 0;
}

Reading and Writing an Array of Elements in Binary Format


#include <stdio.h>
struct Student
{
int RollNo;
char Name[30];
double Marks;
};
int main()
{
struct Student s1[3],s2[3];
int i;
FILE *file = fopen("d:\\student.dat","w+b");
if (file == NULL)
{
printf("Error in saving student data");
return 1;
}
for(i=0;i<3;i++)
{
printf("Enter RollNo: ");
scanf("%d",&s1[i].RollNo);
printf("Enter Name: ");
scanf("%s",&s1[i].Name);
printf("Enter Marks: ");
scanf("%lf",&s1[i].Marks);
}
fwrite(s1,sizeof(s1[0]),3,file);
fseek(file,0,0);
fread(s2,sizeof(s2[0]),3,file);
for(i=0;i<3;i++)
printf("%d %s %lf\n",s2[i].RollNo,s2[i].Name,s2[i].Marks);
fclose(file);
C Programming Language File Handling

return 0;
}

You might also like