SlideShare a Scribd company logo
FILES
Introduction to Files
So far, the operations using C program are done on a prompt / terminal
which is not stored anywhere. But in the software industry, most of the
programs are written to store the information fetched from the program.
One such way is to store the fetched information in a file. Different
operations that can be performed on a file are:
1. Creation of a new file
2. Opening an existing file
3. Reading from file
4. Writing to a file
5. Move the pointer to a specific location in a file
6. Closing a file
What is a File?
• A file can be treated as external storage. It consists of a sequence of bytes
residing on the disk.
• A program can create, read, and write into a file. Unlike an array, the data
in the file is retained even after the program finishes its execution. It's a
permanent storage medium.
• File handling in C programming uses FILE STREAM as a means of
communication between programs and data files.
• The INPUT STREAM extracts the data from the files and supplies it to the
program.
• The OUTPUT STREAM stores the data into the file supplied by the program.
• C uses a structure called FILE (defined in stdio.h) to store the attributes of a
file.
Declaring a File Pointer
• In C language, in order to declare a file, we use a file pointer. A file
pointer is a pointer variable that specifies the next byte to be read or
written to.
• Every time a file is opened, the file pointer points to the beginning of
the file. A file is declared as follows:
• FILE *fp;
• //fp is the name of the file pointer
The basic File operations
 Open a file
 Read data from a file
 Write data into a file
 Close a file
Library Functions for FILE handling
No. Function Description
1 fopen() opens new or existing file
2 fprintf() write data into the file
3 fscanf() reads data from the file
4 fputc() writes a character into the file
5 fgetc() reads a character from file
6 fclose() closes the file
7 fseek() sets the file pointer to given position
8 fputw() writes an integer to file
9 fgetw() reads an integer from file
10 ftell() returns current position
11 rewind() sets the file pointer to the beginning of the file
Opening File: fopen()
• The fopen() function is used to open a file. The syntax of the fopen() is
given below.
• fp = FILE *fopen(const char *filename, const char *mode);
• fp is the file pointer that holds the reference to the file, the filename is
the name of the file to be opened or created, and mode specifies the
purpose of opening a file such as for reading or writing.
• FILE is an object type used for storing information about the file
stream.
Opening File: fopen()
• A file can be opened in
different modes. Below
are some of the most
commonly used modes for
opening or creating a file.
Mode Description
r opens a text file in read mode
w opens a text file in write mode
a opens a text file in append mode
r+ opens a text file in read and write mode
w+ opens a text file in read and write mode
a+ opens a text file in read and write mode
rb opens a binary file in read mode
wb opens a binary file in write mode
ab opens a binary file in append mode
rb+ opens a binary file in read and write mode
wb+ opens a binary file in read and write mode
ab+ opens a binary file in read and write mode
#include<stdio.h>
void main( )
{
FILE *fp ;
char ch ;
fp = fopen("file_handle.c","r") ;
while ( 1 )
{
ch = fgetc ( fp ) ;
if ( ch == EOF )
break ;
printf("%c",ch) ;
}
fclose (fp ) ;
}
Opening File: fopen()
• A file needs to be closed after a read or write operation to release the
memory allocated by the program.
• In C, a file is closed using the fclose() function.
• This returns 0 on success and EOF in the case of a failure.
• An EOF is defined in the library called stdio.h.
• EOF is a constant defined as a negative integer value which denotes
that the end of the file has reached.
Syntax: fclose( FILE *fp );
Closing File: fclose()
Writing and Reading Functions
1. getc(): Read a single character from the opened file
2. putc(): Write a single character from the opened file
3. fgetc(): Reads a character from the file with the help of the file pointer fp. It returns EOF at
the end of the file
4. fputc(): Writes a character into the file with the help of the file pointer fp. It returns EOF in
the case of an error
5. fgets(): Read a line of message from the file.
6. fputs(): Write’s a line of message into the file.
7. fprintf(): It sends formatted output to a stream.
8. fscanf(): It reads formatted data from the stream.
9. putw(): Write’s an integer data into a file.
10.getw(): Read integer data from the file.
getc(): Read a single character
getc():
This function reads a single character from the opened file and moves
the file pointer. It returns EOF if end of file reached.
Syntax: char ch=getc(fp);
It is available in conio.h
#include<stdio.h>
#include<conio.h>
void main()
{
FILE *f;
char c;
f = fopen(“list.txt”, “r”);
if(f == NULL)
ptintf(“File not find”);
else
while(c = getc(f)) != EOF)
printf(“%c”,c);
fclose(f);
}
getc(): Example
putc(): Write a single character
putc():
This function is used to write a single character into a file. If an error
occurs it returns EOF.
Syntax: putc( ch, Fp );
‘Fp’ indicates File pointer.
#include<stdio.h>
#include<conio.h>
void main()
{
FILE *f;
char c;
ptintf(“Enter few words and ‘*’ to exit”);
f = fopen(“words.txt”, “w”);
while( (c = getchar()) != ‘*’ )
putc(c , f);
fclose(f);
}
putc(): Example
fputc(): Write a single character
fputc():
This function writes a character c into the file with the help of the file
pointer fp. It returns EOF in the case of an error.
Syntax: int fputc( int c, FILE *fp );
#include<stdio.h>
#include<conio.h>
void main()
{
FILE *fp;
fp = fopen("file1.txt", "w");//opening file
fputc('a',fp);//writing single character into file
fclose(fp);
}
fputc(): Example
fgetc(): Read a single character
fgetc():
The fgetc() function returns a single character from the file. It gets a
character from the stream. It returns EOF at the end of file.
Syntax: int fgetc(FILE *fp)
#include<stdio.h>
#include<conio.h>
void main()
{
FILE *fp;
char c;
fp=fopen("myfile.txt","r");
while((c=fgetc(fp))!=EOF)
printf("%c",c);
fclose(fp);
}
fgetc(): Example
fputs() and fgets()
The fputs() and fgets() in C programming are used to write and read
string from stream
fputs():
The fputs() function writes a line of characters into file. It outputs string
to a stream.
Syntax: int fputs( const char *s, FILE *fp );
This function writes string s to the file with the help of the reference
pointer fp.
#include<stdio.h>
#include<conio.h>
void main()
{
FILE *fp;
fp=fopen("myfile2.txt","w");
fputs("hello c programming",fp);
fclose(fp);
}
fputs(): Example
fputs() and fgets()
fgets():
The fgets() function reads a line of characters from file. It gets string
from a stream.
Syntax: char *fgets( char *buffer, int n, FILE *fp );
fgets() reads up to n characters from the input stream referenced by fp.
The string reads and copied into the character buffer and terminates
when a null character is encountered.
#include<stdio.h>
#include<conio.h>
void main()
{
FILE *fp;
char text[300];
fp=fopen("myfile2.txt","r");
printf("%s",fgets(text,200,fp));
fclose(fp);
}
fgets(): Example
fprintf() and fscanf()
fprintf():
The fprintf() function is used to write set of characters into file. It sends
formatted output to a stream.
Syntax: int fprintf(FILE *fp, const char *format)
#include<stdio.h>
#include<conio.h>
void main()
{
FILE *fp;
fp = fopen("file.txt", "w");//opening file
fprintf(fp, "Hello file by fprintf...n");//writing data into file
fclose(fp);
}
fprintf(): Example
fprintf() and fscanf()
fscanf():
The fscanf() function is used to read set of characters from file. It reads
a word from the file and returns EOF at the end of file.
Syntax: int fscanf(FILE *fp, const char *format , ..)
#include<stdio.h>
#include<conio.h>
void main()
{
FILE *fp;
char buff[255];//creating char array to store data of file
fp = fopen("file.txt", "r");
while(fscanf(fp, "%s", buff)!=EOF)
printf("%s ", buff );
fclose(fp);
}
fscanf(): Example
#include<stdio.h>
#include<conio.h>
void main()
{
FILE *fptr;
int id;
char name[30];
float salary;
fptr = fopen("emp.txt", "w+");
if (fptr == NULL)
{
printf("File does not exists n");
return 0;
}
fscanf(): Example
#include<stdio.h>
#include<conio.h>
void main()
{
FILE *fptr;
int id;
char name[30];
float salary;
fptr = fopen("emp.txt", "w+");
if (fptr == NULL)
{
printf("File does not exists n");
return 0;
}
Hold employee information in to a File
printf("Enter the idn");
scanf("%d", &id);
fprintf(fptr, "Id= %dn", id);
printf("Enter the name n");
scanf("%s", name);
fprintf(fptr, "Name= %sn", name);
printf("Enter the salaryn");
scanf("%f", &salary);
fprintf(fptr, "Salary= %.2fn", salary);
fclose(fptr);
}
getw() and putw()
putw():
This function is used to write an integer value to file. This function
deals with integer data only.
Syntax: putw( int v, FILE *FP);
getw():
This function returns the integer value from a file and increments the
file pointer. This function deals with only integers.
Syntax: int getw( FILE *FP );
Block Input and Output
• It is important to know how numerical data is stored on the disk by fprintf() function.
• Text and characters requires one byte for storing them with fprintf(). Similarly for storing
numbers in memory two bytes and for floats four bytes.
• For example 3456 occupies two bytes in memory. But when it is transferred to the disk
file using fprint() function it would occupies four bytes. For each character it
requires one byte. Even for float also each digit including dot(.) requires one byte.
• Thus large amount of integers and float data requires large space on the disk. To
overcome this problem files should be read and write in binary mode, for which we use
fread() and fwrite() functions.
• fwrite(): This function is used for writing an entire structure block to a given file.
• fread(): This function is used for reading an entire block from a given file.
#include<stdio.h>
#include<conio.h>
void main()
{
struct
{
char name[20];
int age;
}stud[50],s1[50];
FILE *fp;
int i, j=0, n;
char str[15];
printf(“Enter File Name:”);
scanf(“%s”,str);
fp = fopen(str, “rb”);
if( fp == NULL)
puts(“File does not exist”);
Block Input and Output
else
{
puts(“How many records:”);
scanf(“%d”, &n);
for(i=0;i<n;i++)
{
puts(“Name:” );
scanf(“%s”, &stud[i].name);
puts(“Age:” );
scanf(“%s”, &stud[i].age);
}
j=n;
while(n !=0 )
{
fwrite(&stud, sizeof(stud), 1, fp);
n--;
}
Block Input and Output
for(i=0; i<j ; i++ )
{
fread(&s1, sizeof(s1), 1, fp);
printf(“Name %s t Age %d n”, s1[i].name, s1[i].age);
}
}//else close
fclose(fp);
}//main close
Block Input and Output
fseek() function
The fseek() function is used to set the file pointer to the specified offset. It is used to write data into
file at desired location.
Syntax: int fseek(FILE *stream, long int offset, int position)
Three are arguments are to be passed through this function. They are:
1. File pointer
2. Offset: offset may be positive (moving in forward from current position) or negative (moving
backwards). The offset being a variable of type long.
3. The current position of file pointer.
• There are 3 constants used in the fseek() function for position: SEEK_SET, SEEK_CUR and
SEEK_END
Integer
value
Constant Location in the File
0 SEEK_SET Beginning of the file
1 SEEK_CUR Current position of the file pointer
2 SEEK_END End of the file
#include <stdio.h>
void main(){
FILE *fp;
fp = fopen("myfile.txt","w+");
fputs("This is a C program", fp);
fseek( fp, 7, SEEK_SET );
fputs("File handling in C", fp);
fclose(fp);
}
fseek() Example
myfile.txt
This is File handling in C
rewind() function
The rewind() function sets the file pointer at the beginning of the stream. It
is useful if you have to use stream many times.
Syntax: void rewind(FILE *stream)
Example:
File: file.txt
this is a simple text
File Name: rewind.c
#include<stdio.h>
void main(){
FILE *fp;
char c;
fp=fopen("file.txt","r");
while((c=fgetc(fp))!=EOF)
printf("%c",c);
rewind(fp);//moves the file pointer at beginning of the file
while((c=fgetc(fp))!=EOF)
printf("%c",c);
fclose(fp);
}
rewind() Example
File: file.txt
this is a simple text
Output:
this is a simple textthis is a simple text
ftell() function
• The ftell() function returns the current file position of the specified stream.
• We can use ftell() function to get the total size of a file after moving file
pointer at the end of file.
• We can use SEEK_END constant to move the file pointer at the end of file.
Syntax: long int ftell(FILE *stream)
File Name: ftell.c
#include <stdio.h>
void main (){
FILE *fp;
int length;
fp = fopen("file.txt", "r");
fseek(fp, 0, SEEK_END);
length = ftell(fp);
fclose(fp);
printf("Size of file: %d bytes", length);
}
ftell() Example
File: file.txt
this is a simple text
Output:
Size of file: 21 bytes
want to learn files,then just use this ppt to learn
Ad

More Related Content

Similar to want to learn files,then just use this ppt to learn (20)

pre processor and file handling in c language ppt
pre processor and file handling in c language pptpre processor and file handling in c language ppt
pre processor and file handling in c language ppt
shreyasreddy703
 
Data Structure Using C - FILES
Data Structure Using C - FILESData Structure Using C - FILES
Data Structure Using C - FILES
Harish Kamat
 
Module 03 File Handling in C
Module 03 File Handling in CModule 03 File Handling in C
Module 03 File Handling in C
Tushar B Kute
 
file handling in c programming with file functions
file handling in c programming with file functionsfile handling in c programming with file functions
file handling in c programming with file functions
10300PEDDIKISHOR
 
Lecture 20 - File Handling
Lecture 20 - File HandlingLecture 20 - File Handling
Lecture 20 - File Handling
Md. Imran Hossain Showrov
 
Understanding c file handling functions with examples
Understanding c file handling functions with examplesUnderstanding c file handling functions with examples
Understanding c file handling functions with examples
Muhammed Thanveer M
 
Unit 8
Unit 8Unit 8
Unit 8
Keerthi Mutyala
 
File handling in c
File handling in cFile handling in c
File handling in c
aakanksha s
 
Handout#01
Handout#01Handout#01
Handout#01
Sunita Milind Dol
 
Unit5 C
Unit5 C Unit5 C
Unit5 C
arnold 7490
 
ppt5-190810161800 (1).pdf
ppt5-190810161800 (1).pdfppt5-190810161800 (1).pdf
ppt5-190810161800 (1).pdf
MalligaarjunanN
 
file_handling_in_c.ppt
file_handling_in_c.pptfile_handling_in_c.ppt
file_handling_in_c.ppt
yuvrajkeshri
 
Module 5 file cp
Module 5 file cpModule 5 file cp
Module 5 file cp
Amarjith C K
 
files c programming handling in computer programming
files c programming handling in computer programmingfiles c programming handling in computer programming
files c programming handling in computer programming
chatakonduyaswanth24
 
Chap 12(files)
Chap 12(files)Chap 12(files)
Chap 12(files)
Bangabandhu Sheikh Mujibur Rahman Science and Technology University
 
File handling
File handlingFile handling
File handling
Ans Ali
 
PPS PPT 2.pptx
PPS PPT 2.pptxPPS PPT 2.pptx
PPS PPT 2.pptx
Sandeepbhuma1
 
Unit v
Unit vUnit v
Unit v
kannaki
 
Chapter 13.1.10
Chapter 13.1.10Chapter 13.1.10
Chapter 13.1.10
patcha535
 
File management
File managementFile management
File management
sumathiv9
 

Recently uploaded (20)

Stein, Hunt, Green letter to Congress April 2025
Stein, Hunt, Green letter to Congress April 2025Stein, Hunt, Green letter to Congress April 2025
Stein, Hunt, Green letter to Congress April 2025
Mebane Rash
 
APM Midlands Region April 2025 Sacha Hind Circulated.pdf
APM Midlands Region April 2025 Sacha Hind Circulated.pdfAPM Midlands Region April 2025 Sacha Hind Circulated.pdf
APM Midlands Region April 2025 Sacha Hind Circulated.pdf
Association for Project Management
 
Geography Sem II Unit 1C Correlation of Geography with other school subjects
Geography Sem II Unit 1C Correlation of Geography with other school subjectsGeography Sem II Unit 1C Correlation of Geography with other school subjects
Geography Sem II Unit 1C Correlation of Geography with other school subjects
ProfDrShaikhImran
 
03#UNTAGGED. Generosity in architecture.
03#UNTAGGED. Generosity in architecture.03#UNTAGGED. Generosity in architecture.
03#UNTAGGED. Generosity in architecture.
MCH
 
One Hot encoding a revolution in Machine learning
One Hot encoding a revolution in Machine learningOne Hot encoding a revolution in Machine learning
One Hot encoding a revolution in Machine learning
momer9505
 
World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...
World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...
World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...
larencebapu132
 
K12 Tableau Tuesday - Algebra Equity and Access in Atlanta Public Schools
K12 Tableau Tuesday  - Algebra Equity and Access in Atlanta Public SchoolsK12 Tableau Tuesday  - Algebra Equity and Access in Atlanta Public Schools
K12 Tableau Tuesday - Algebra Equity and Access in Atlanta Public Schools
dogden2
 
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - WorksheetCBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
Sritoma Majumder
 
How to Manage Opening & Closing Controls in Odoo 17 POS
How to Manage Opening & Closing Controls in Odoo 17 POSHow to Manage Opening & Closing Controls in Odoo 17 POS
How to Manage Opening & Closing Controls in Odoo 17 POS
Celine George
 
THE STG QUIZ GROUP D.pptx quiz by Ridip Hazarika
THE STG QUIZ GROUP D.pptx   quiz by Ridip HazarikaTHE STG QUIZ GROUP D.pptx   quiz by Ridip Hazarika
THE STG QUIZ GROUP D.pptx quiz by Ridip Hazarika
Ridip Hazarika
 
Contact Lens:::: An Overview.pptx.: Optometry
Contact Lens:::: An Overview.pptx.: OptometryContact Lens:::: An Overview.pptx.: Optometry
Contact Lens:::: An Overview.pptx.: Optometry
MushahidRaza8
 
Link your Lead Opportunities into Spreadsheet using odoo CRM
Link your Lead Opportunities into Spreadsheet using odoo CRMLink your Lead Opportunities into Spreadsheet using odoo CRM
Link your Lead Opportunities into Spreadsheet using odoo CRM
Celine George
 
Understanding P–N Junction Semiconductors: A Beginner’s Guide
Understanding P–N Junction Semiconductors: A Beginner’s GuideUnderstanding P–N Junction Semiconductors: A Beginner’s Guide
Understanding P–N Junction Semiconductors: A Beginner’s Guide
GS Virdi
 
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
Celine George
 
Political History of Pala dynasty Pala Rulers NEP.pptx
Political History of Pala dynasty Pala Rulers NEP.pptxPolitical History of Pala dynasty Pala Rulers NEP.pptx
Political History of Pala dynasty Pala Rulers NEP.pptx
Arya Mahila P. G. College, Banaras Hindu University, Varanasi, India.
 
Sugar-Sensing Mechanism in plants....pptx
Sugar-Sensing Mechanism in plants....pptxSugar-Sensing Mechanism in plants....pptx
Sugar-Sensing Mechanism in plants....pptx
Dr. Renu Jangid
 
Exercise Physiology MCQS By DR. NASIR MUSTAFA
Exercise Physiology MCQS By DR. NASIR MUSTAFAExercise Physiology MCQS By DR. NASIR MUSTAFA
Exercise Physiology MCQS By DR. NASIR MUSTAFA
Dr. Nasir Mustafa
 
SCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptx
SCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptxSCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptx
SCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptx
Ronisha Das
 
To study Digestive system of insect.pptx
To study Digestive system of insect.pptxTo study Digestive system of insect.pptx
To study Digestive system of insect.pptx
Arshad Shaikh
 
Engage Donors Through Powerful Storytelling.pdf
Engage Donors Through Powerful Storytelling.pdfEngage Donors Through Powerful Storytelling.pdf
Engage Donors Through Powerful Storytelling.pdf
TechSoup
 
Stein, Hunt, Green letter to Congress April 2025
Stein, Hunt, Green letter to Congress April 2025Stein, Hunt, Green letter to Congress April 2025
Stein, Hunt, Green letter to Congress April 2025
Mebane Rash
 
Geography Sem II Unit 1C Correlation of Geography with other school subjects
Geography Sem II Unit 1C Correlation of Geography with other school subjectsGeography Sem II Unit 1C Correlation of Geography with other school subjects
Geography Sem II Unit 1C Correlation of Geography with other school subjects
ProfDrShaikhImran
 
03#UNTAGGED. Generosity in architecture.
03#UNTAGGED. Generosity in architecture.03#UNTAGGED. Generosity in architecture.
03#UNTAGGED. Generosity in architecture.
MCH
 
One Hot encoding a revolution in Machine learning
One Hot encoding a revolution in Machine learningOne Hot encoding a revolution in Machine learning
One Hot encoding a revolution in Machine learning
momer9505
 
World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...
World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...
World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...
larencebapu132
 
K12 Tableau Tuesday - Algebra Equity and Access in Atlanta Public Schools
K12 Tableau Tuesday  - Algebra Equity and Access in Atlanta Public SchoolsK12 Tableau Tuesday  - Algebra Equity and Access in Atlanta Public Schools
K12 Tableau Tuesday - Algebra Equity and Access in Atlanta Public Schools
dogden2
 
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - WorksheetCBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
Sritoma Majumder
 
How to Manage Opening & Closing Controls in Odoo 17 POS
How to Manage Opening & Closing Controls in Odoo 17 POSHow to Manage Opening & Closing Controls in Odoo 17 POS
How to Manage Opening & Closing Controls in Odoo 17 POS
Celine George
 
THE STG QUIZ GROUP D.pptx quiz by Ridip Hazarika
THE STG QUIZ GROUP D.pptx   quiz by Ridip HazarikaTHE STG QUIZ GROUP D.pptx   quiz by Ridip Hazarika
THE STG QUIZ GROUP D.pptx quiz by Ridip Hazarika
Ridip Hazarika
 
Contact Lens:::: An Overview.pptx.: Optometry
Contact Lens:::: An Overview.pptx.: OptometryContact Lens:::: An Overview.pptx.: Optometry
Contact Lens:::: An Overview.pptx.: Optometry
MushahidRaza8
 
Link your Lead Opportunities into Spreadsheet using odoo CRM
Link your Lead Opportunities into Spreadsheet using odoo CRMLink your Lead Opportunities into Spreadsheet using odoo CRM
Link your Lead Opportunities into Spreadsheet using odoo CRM
Celine George
 
Understanding P–N Junction Semiconductors: A Beginner’s Guide
Understanding P–N Junction Semiconductors: A Beginner’s GuideUnderstanding P–N Junction Semiconductors: A Beginner’s Guide
Understanding P–N Junction Semiconductors: A Beginner’s Guide
GS Virdi
 
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
Celine George
 
Sugar-Sensing Mechanism in plants....pptx
Sugar-Sensing Mechanism in plants....pptxSugar-Sensing Mechanism in plants....pptx
Sugar-Sensing Mechanism in plants....pptx
Dr. Renu Jangid
 
Exercise Physiology MCQS By DR. NASIR MUSTAFA
Exercise Physiology MCQS By DR. NASIR MUSTAFAExercise Physiology MCQS By DR. NASIR MUSTAFA
Exercise Physiology MCQS By DR. NASIR MUSTAFA
Dr. Nasir Mustafa
 
SCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptx
SCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptxSCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptx
SCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptx
Ronisha Das
 
To study Digestive system of insect.pptx
To study Digestive system of insect.pptxTo study Digestive system of insect.pptx
To study Digestive system of insect.pptx
Arshad Shaikh
 
Engage Donors Through Powerful Storytelling.pdf
Engage Donors Through Powerful Storytelling.pdfEngage Donors Through Powerful Storytelling.pdf
Engage Donors Through Powerful Storytelling.pdf
TechSoup
 
Ad

want to learn files,then just use this ppt to learn

  • 2. Introduction to Files So far, the operations using C program are done on a prompt / terminal which is not stored anywhere. But in the software industry, most of the programs are written to store the information fetched from the program. One such way is to store the fetched information in a file. Different operations that can be performed on a file are: 1. Creation of a new file 2. Opening an existing file 3. Reading from file 4. Writing to a file 5. Move the pointer to a specific location in a file 6. Closing a file
  • 3. What is a File? • A file can be treated as external storage. It consists of a sequence of bytes residing on the disk. • A program can create, read, and write into a file. Unlike an array, the data in the file is retained even after the program finishes its execution. It's a permanent storage medium. • File handling in C programming uses FILE STREAM as a means of communication between programs and data files. • The INPUT STREAM extracts the data from the files and supplies it to the program. • The OUTPUT STREAM stores the data into the file supplied by the program. • C uses a structure called FILE (defined in stdio.h) to store the attributes of a file.
  • 4. Declaring a File Pointer • In C language, in order to declare a file, we use a file pointer. A file pointer is a pointer variable that specifies the next byte to be read or written to. • Every time a file is opened, the file pointer points to the beginning of the file. A file is declared as follows: • FILE *fp; • //fp is the name of the file pointer
  • 5. The basic File operations  Open a file  Read data from a file  Write data into a file  Close a file
  • 6. Library Functions for FILE handling No. Function Description 1 fopen() opens new or existing file 2 fprintf() write data into the file 3 fscanf() reads data from the file 4 fputc() writes a character into the file 5 fgetc() reads a character from file 6 fclose() closes the file 7 fseek() sets the file pointer to given position 8 fputw() writes an integer to file 9 fgetw() reads an integer from file 10 ftell() returns current position 11 rewind() sets the file pointer to the beginning of the file
  • 7. Opening File: fopen() • The fopen() function is used to open a file. The syntax of the fopen() is given below. • fp = FILE *fopen(const char *filename, const char *mode); • fp is the file pointer that holds the reference to the file, the filename is the name of the file to be opened or created, and mode specifies the purpose of opening a file such as for reading or writing. • FILE is an object type used for storing information about the file stream.
  • 8. Opening File: fopen() • A file can be opened in different modes. Below are some of the most commonly used modes for opening or creating a file. Mode Description r opens a text file in read mode w opens a text file in write mode a opens a text file in append mode r+ opens a text file in read and write mode w+ opens a text file in read and write mode a+ opens a text file in read and write mode rb opens a binary file in read mode wb opens a binary file in write mode ab opens a binary file in append mode rb+ opens a binary file in read and write mode wb+ opens a binary file in read and write mode ab+ opens a binary file in read and write mode
  • 9. #include<stdio.h> void main( ) { FILE *fp ; char ch ; fp = fopen("file_handle.c","r") ; while ( 1 ) { ch = fgetc ( fp ) ; if ( ch == EOF ) break ; printf("%c",ch) ; } fclose (fp ) ; } Opening File: fopen()
  • 10. • A file needs to be closed after a read or write operation to release the memory allocated by the program. • In C, a file is closed using the fclose() function. • This returns 0 on success and EOF in the case of a failure. • An EOF is defined in the library called stdio.h. • EOF is a constant defined as a negative integer value which denotes that the end of the file has reached. Syntax: fclose( FILE *fp ); Closing File: fclose()
  • 11. Writing and Reading Functions 1. getc(): Read a single character from the opened file 2. putc(): Write a single character from the opened file 3. fgetc(): Reads a character from the file with the help of the file pointer fp. It returns EOF at the end of the file 4. fputc(): Writes a character into the file with the help of the file pointer fp. It returns EOF in the case of an error 5. fgets(): Read a line of message from the file. 6. fputs(): Write’s a line of message into the file. 7. fprintf(): It sends formatted output to a stream. 8. fscanf(): It reads formatted data from the stream. 9. putw(): Write’s an integer data into a file. 10.getw(): Read integer data from the file.
  • 12. getc(): Read a single character getc(): This function reads a single character from the opened file and moves the file pointer. It returns EOF if end of file reached. Syntax: char ch=getc(fp); It is available in conio.h
  • 13. #include<stdio.h> #include<conio.h> void main() { FILE *f; char c; f = fopen(“list.txt”, “r”); if(f == NULL) ptintf(“File not find”); else while(c = getc(f)) != EOF) printf(“%c”,c); fclose(f); } getc(): Example
  • 14. putc(): Write a single character putc(): This function is used to write a single character into a file. If an error occurs it returns EOF. Syntax: putc( ch, Fp ); ‘Fp’ indicates File pointer.
  • 15. #include<stdio.h> #include<conio.h> void main() { FILE *f; char c; ptintf(“Enter few words and ‘*’ to exit”); f = fopen(“words.txt”, “w”); while( (c = getchar()) != ‘*’ ) putc(c , f); fclose(f); } putc(): Example
  • 16. fputc(): Write a single character fputc(): This function writes a character c into the file with the help of the file pointer fp. It returns EOF in the case of an error. Syntax: int fputc( int c, FILE *fp );
  • 17. #include<stdio.h> #include<conio.h> void main() { FILE *fp; fp = fopen("file1.txt", "w");//opening file fputc('a',fp);//writing single character into file fclose(fp); } fputc(): Example
  • 18. fgetc(): Read a single character fgetc(): The fgetc() function returns a single character from the file. It gets a character from the stream. It returns EOF at the end of file. Syntax: int fgetc(FILE *fp)
  • 19. #include<stdio.h> #include<conio.h> void main() { FILE *fp; char c; fp=fopen("myfile.txt","r"); while((c=fgetc(fp))!=EOF) printf("%c",c); fclose(fp); } fgetc(): Example
  • 20. fputs() and fgets() The fputs() and fgets() in C programming are used to write and read string from stream fputs(): The fputs() function writes a line of characters into file. It outputs string to a stream. Syntax: int fputs( const char *s, FILE *fp ); This function writes string s to the file with the help of the reference pointer fp.
  • 22. fputs() and fgets() fgets(): The fgets() function reads a line of characters from file. It gets string from a stream. Syntax: char *fgets( char *buffer, int n, FILE *fp ); fgets() reads up to n characters from the input stream referenced by fp. The string reads and copied into the character buffer and terminates when a null character is encountered.
  • 23. #include<stdio.h> #include<conio.h> void main() { FILE *fp; char text[300]; fp=fopen("myfile2.txt","r"); printf("%s",fgets(text,200,fp)); fclose(fp); } fgets(): Example
  • 24. fprintf() and fscanf() fprintf(): The fprintf() function is used to write set of characters into file. It sends formatted output to a stream. Syntax: int fprintf(FILE *fp, const char *format)
  • 25. #include<stdio.h> #include<conio.h> void main() { FILE *fp; fp = fopen("file.txt", "w");//opening file fprintf(fp, "Hello file by fprintf...n");//writing data into file fclose(fp); } fprintf(): Example
  • 26. fprintf() and fscanf() fscanf(): The fscanf() function is used to read set of characters from file. It reads a word from the file and returns EOF at the end of file. Syntax: int fscanf(FILE *fp, const char *format , ..)
  • 27. #include<stdio.h> #include<conio.h> void main() { FILE *fp; char buff[255];//creating char array to store data of file fp = fopen("file.txt", "r"); while(fscanf(fp, "%s", buff)!=EOF) printf("%s ", buff ); fclose(fp); } fscanf(): Example
  • 28. #include<stdio.h> #include<conio.h> void main() { FILE *fptr; int id; char name[30]; float salary; fptr = fopen("emp.txt", "w+"); if (fptr == NULL) { printf("File does not exists n"); return 0; } fscanf(): Example
  • 29. #include<stdio.h> #include<conio.h> void main() { FILE *fptr; int id; char name[30]; float salary; fptr = fopen("emp.txt", "w+"); if (fptr == NULL) { printf("File does not exists n"); return 0; } Hold employee information in to a File printf("Enter the idn"); scanf("%d", &id); fprintf(fptr, "Id= %dn", id); printf("Enter the name n"); scanf("%s", name); fprintf(fptr, "Name= %sn", name); printf("Enter the salaryn"); scanf("%f", &salary); fprintf(fptr, "Salary= %.2fn", salary); fclose(fptr); }
  • 30. getw() and putw() putw(): This function is used to write an integer value to file. This function deals with integer data only. Syntax: putw( int v, FILE *FP); getw(): This function returns the integer value from a file and increments the file pointer. This function deals with only integers. Syntax: int getw( FILE *FP );
  • 31. Block Input and Output • It is important to know how numerical data is stored on the disk by fprintf() function. • Text and characters requires one byte for storing them with fprintf(). Similarly for storing numbers in memory two bytes and for floats four bytes. • For example 3456 occupies two bytes in memory. But when it is transferred to the disk file using fprint() function it would occupies four bytes. For each character it requires one byte. Even for float also each digit including dot(.) requires one byte. • Thus large amount of integers and float data requires large space on the disk. To overcome this problem files should be read and write in binary mode, for which we use fread() and fwrite() functions. • fwrite(): This function is used for writing an entire structure block to a given file. • fread(): This function is used for reading an entire block from a given file.
  • 32. #include<stdio.h> #include<conio.h> void main() { struct { char name[20]; int age; }stud[50],s1[50]; FILE *fp; int i, j=0, n; char str[15]; printf(“Enter File Name:”); scanf(“%s”,str); fp = fopen(str, “rb”); if( fp == NULL) puts(“File does not exist”); Block Input and Output
  • 33. else { puts(“How many records:”); scanf(“%d”, &n); for(i=0;i<n;i++) { puts(“Name:” ); scanf(“%s”, &stud[i].name); puts(“Age:” ); scanf(“%s”, &stud[i].age); } j=n; while(n !=0 ) { fwrite(&stud, sizeof(stud), 1, fp); n--; } Block Input and Output
  • 34. for(i=0; i<j ; i++ ) { fread(&s1, sizeof(s1), 1, fp); printf(“Name %s t Age %d n”, s1[i].name, s1[i].age); } }//else close fclose(fp); }//main close Block Input and Output
  • 35. fseek() function The fseek() function is used to set the file pointer to the specified offset. It is used to write data into file at desired location. Syntax: int fseek(FILE *stream, long int offset, int position) Three are arguments are to be passed through this function. They are: 1. File pointer 2. Offset: offset may be positive (moving in forward from current position) or negative (moving backwards). The offset being a variable of type long. 3. The current position of file pointer. • There are 3 constants used in the fseek() function for position: SEEK_SET, SEEK_CUR and SEEK_END Integer value Constant Location in the File 0 SEEK_SET Beginning of the file 1 SEEK_CUR Current position of the file pointer 2 SEEK_END End of the file
  • 36. #include <stdio.h> void main(){ FILE *fp; fp = fopen("myfile.txt","w+"); fputs("This is a C program", fp); fseek( fp, 7, SEEK_SET ); fputs("File handling in C", fp); fclose(fp); } fseek() Example myfile.txt This is File handling in C
  • 37. rewind() function The rewind() function sets the file pointer at the beginning of the stream. It is useful if you have to use stream many times. Syntax: void rewind(FILE *stream) Example: File: file.txt this is a simple text
  • 38. File Name: rewind.c #include<stdio.h> void main(){ FILE *fp; char c; fp=fopen("file.txt","r"); while((c=fgetc(fp))!=EOF) printf("%c",c); rewind(fp);//moves the file pointer at beginning of the file while((c=fgetc(fp))!=EOF) printf("%c",c); fclose(fp); } rewind() Example File: file.txt this is a simple text Output: this is a simple textthis is a simple text
  • 39. ftell() function • The ftell() function returns the current file position of the specified stream. • We can use ftell() function to get the total size of a file after moving file pointer at the end of file. • We can use SEEK_END constant to move the file pointer at the end of file. Syntax: long int ftell(FILE *stream)
  • 40. File Name: ftell.c #include <stdio.h> void main (){ FILE *fp; int length; fp = fopen("file.txt", "r"); fseek(fp, 0, SEEK_END); length = ftell(fp); fclose(fp); printf("Size of file: %d bytes", length); } ftell() Example File: file.txt this is a simple text Output: Size of file: 21 bytes