SlideShare a Scribd company logo
File Handling in C
What is a File?
• A file is a collection of related data that a computers
treats as a single unit.
• Computers store files to secondary storage so that
the contents of files remain intact when a computer
shuts down.
• When a computer reads a file, it copies the file from
the storage device to memory; when it writes to a
file, it transfers data from memory to the storage
device.
• C uses a structure called FILE (defined in
stdio.h) to store the attributes of a file.
Steps in Processing a File
1. Create the stream via a pointer variable using
the FILE structure:
FILE *p;
2. Open the file, associating the stream name
with the file name.
3. Read or write the data.
4. Close the file.
The basic file operations are
• fopen - open a file- specify how its opened
(read/write) and type (binary/text)
• fclose - close an opened file
• fread - read from a file
• fwrite - write to a file
• fseek/fsetpos - move a file pointer to somewhere in a
file.
• ftell/fgetpos - tell you where the file pointer is
located.
File Open Modes
from Table 7-1 in Forouzan & Gilberg, p. 400
More on File Open Modes
from Figure 7-4 in Forouzan & Gilberg, p. 401
Additionally,
• r+ - open for reading and writing, start at
beginning
• w+ - open for reading and writing (overwrite
file)
• a+ - open for reading and writing (append if
file exists)
File Open
• The file open function (fopen) serves two
purposes:
– It makes the connection between the physical file
and the stream.
– It creates “a program file structure to store the
information” C needs to process the file.
• Syntax:
filepointer=fopen(“filename”, “mode”);
More On fopen
• The file mode tells C how the program will use
the file.
• The filename indicates the system name and
location for the file.
• We assign the return value of fopen to our
pointer variable:
spData = fopen(“MYFILE.TXT”, “w”);
spData = fopen(“A:MYFILE.TXT”, “w”);
More On fopen
from Figure 7-3 in Forouzan & Gilberg, p. 399
Closing a File
• When we finish with a mode, we need to close
the file before ending the program or
beginning another mode with that same file.
• To close a file, we use fclose and the
pointer variable:
fclose(spData);
fprintf()
Syntax:
fprintf (fp,"string",variables);
Example:
int i = 12;
float x = 2.356;
char ch = 's';
FILE *fp;
fp=fopen(“out.txt”,”w”);
fprintf (fp, "%d %f %c", i, x, ch);
fscanf()
Syntax:
fscanf (fp,"string",identifiers);
Example:
FILE *fp;
Fp=fopen(“input.txt”,”r”);
int i;
fscanf (fp,“%d",i);
getc()
Syntax:
identifier = getc (file pointer);
Example:
FILE *fp;
fp=fopen(“input.txt”,”r”);
char ch;
ch = getc (fp);
putc()
write a single character to the output file,
pointed to by fp.
Example:
FILE *fp;
char ch;
putc (ch,fp);
End of File
• There are a number of ways to test for the end-of-file
condition. Another way is to use the value returned by the
fscanf function:
FILE *fptr1;
int istatus ;
istatus = fscanf (fptr1, "%d", &var) ;
if ( istatus == feof(fptr1) )
{
printf ("End-of-file encountered.n”) ;
}
Reading and Writing Files
#include <stdio.h>
int main ( )
{
FILE *outfile, *infile ;
int b = 5, f ;
float a = 13.72, c = 6.68, e, g ;
outfile = fopen ("testdata", "w") ;
fprintf (outfile, “ %f %d %f ", a, b, c) ;
fclose (outfile) ;
infile = fopen ("testdata", "r") ;
fscanf (infile,"%f %d %f", &e, &f, &g) ;
printf (“ %f %d %f n ", a, b, c) ;
printf (“ %f %d %f n ", e, f, g) ;
}
Example
#include <stdio.h>
#include<conio.h>
void main()
{
char ch;
FILE *fp;
fp=fopen("out.txt","r");
while(!feof(fp))
{
ch=getc(fp);
printf("n%c",ch);
}
getch();
}
fread ()
Declaration:
size_t fread(void *ptr, size_t size, size_t n, FILE *stream);
Remarks:
fread reads a specified number of equal-sized
data items from an input stream into a block.
ptr = Points to a block into which data is read
size = Length of each item read, in bytes
n = Number of items read
stream = file pointer
Example
Example:
#include <stdio.h>
int main()
{
FILE *f;
char buffer[11];
if (f = fopen("fred.txt", “r”))
{
fread(buffer, 1, 10, f);
buffer[10] = 0;
fclose(f);
printf("first 10 characters of the file:n%sn", buffer);
}
return 0;
}
fwrite()
Declaration:
size_t fwrite(const void *ptr, size_t size, size_t n, FILE*stream);
Remarks:
fwrite appends a specified number of equal-sized data items to an output file.
ptr = Pointer to any object; the data written begins at ptr
size = Length of each item of data
n =Number of data items to be appended
stream = file pointer
Example
Example:
#include <stdio.h>
int main()
{
char a[10]={'1','2','3','4','5','6','7','8','9','a'};
FILE *fs;
fs=fopen("Project.txt","w");
fwrite(a,1,10,fs);
fclose(fs);
return 0;
}
fseek()
This function sets the file position indicator for the stream pointed to by stream or you can
say it seeks a specified place within a file and modify it.
SEEK_SET Seeks from beginning of file
SEEK_CUR Seeks from current position
SEEK_END Seeks from end of file
Example:
#include <stdio.h>
int main()
{
FILE * f;
f = fopen("myfile.txt", "w");
fputs("Hello World", f);
fseek(f, 6, SEEK_SET); SEEK_CUR, SEEK_END
fputs(" India", f);
fclose(f);
return 0;
}
ftell()
offset = ftell( file pointer );
"ftell" returns the current position for input or output on the file
#include <stdio.h>
int main(void)
{
FILE *stream;
stream = fopen("MYFILE.TXT", "w");
fprintf(stream, "This is a test");
printf("The file pointer is at byte %ldn", ftell(stream));
fclose(stream);
return 0;
}
THANK YOU
Ad

Recommended

PPT
File handling
Ans Ali
 
PPT
File handling-c
CGC Technical campus,Mohali
 
PDF
Module 03 File Handling in C
Tushar B Kute
 
PPT
Lecture 20 - File Handling
Md. Imran Hossain Showrov
 
PPTX
want to learn files,then just use this ppt to learn
nalluribalaji157
 
PPTX
File in C language
Manash Kumar Mondal
 
PPTX
File management
lalithambiga kamaraj
 
PPTX
files c programming handling in computer programming
chatakonduyaswanth24
 
PPT
File handling in c
Vikash Dhal
 
DOCX
Unit 8
Keerthi Mutyala
 
PPTX
Data Structure Using C - FILES
Harish Kamat
 
PPT
File_Handling in C.ppt
lakshmanarao027MVGRC
 
PPT
File_Handling in C.ppt
lakshmanarao027MVGRC
 
PDF
EASY UNDERSTANDING OF FILES IN C LANGUAGE.pdf
sudhakargeruganti
 
PPTX
MODULE 8-File and preprocessor.pptx for c program learners easy learning
a50905877
 
PPT
File in c
Prabhu Govind
 
PPTX
File management
sumathiv9
 
PPTX
File management
AnishaThakkar2
 
PPT
Mesics lecture files in 'c'
eShikshak
 
PPTX
Concept of file handling in c
MugdhaSharma11
 
PPT
File handling in c
David Livingston J
 
PPT
Unit5
mrecedu
 
PPTX
PPS PPT 2.pptx
Sandeepbhuma1
 
PPSX
1file handling
Frijo Francis
 
PPT
file_handling_in_c.ppt
yuvrajkeshri
 
PDF
637225560972186380.pdf
SureshKalirawna
 
PPT
Unit5 C
arnold 7490
 
PPT
c-Functions power point presentation on c functions
10300PEDDIKISHOR
 
PPT
c-step-by-step-execution power point presentation
10300PEDDIKISHOR
 

More Related Content

Similar to file handling in c programming with file functions (20)

PPT
File handling in c
Vikash Dhal
 
DOCX
Unit 8
Keerthi Mutyala
 
PPTX
Data Structure Using C - FILES
Harish Kamat
 
PPT
File_Handling in C.ppt
lakshmanarao027MVGRC
 
PPT
File_Handling in C.ppt
lakshmanarao027MVGRC
 
PDF
EASY UNDERSTANDING OF FILES IN C LANGUAGE.pdf
sudhakargeruganti
 
PPTX
MODULE 8-File and preprocessor.pptx for c program learners easy learning
a50905877
 
PPT
File in c
Prabhu Govind
 
PPTX
File management
sumathiv9
 
PPTX
File management
AnishaThakkar2
 
PPT
Mesics lecture files in 'c'
eShikshak
 
PPTX
Concept of file handling in c
MugdhaSharma11
 
PPT
File handling in c
David Livingston J
 
PPT
Unit5
mrecedu
 
PPTX
PPS PPT 2.pptx
Sandeepbhuma1
 
PPSX
1file handling
Frijo Francis
 
PPT
file_handling_in_c.ppt
yuvrajkeshri
 
PDF
637225560972186380.pdf
SureshKalirawna
 
PPT
Unit5 C
arnold 7490
 
File handling in c
Vikash Dhal
 
Unit 8
Keerthi Mutyala
 
Data Structure Using C - FILES
Harish Kamat
 
File_Handling in C.ppt
lakshmanarao027MVGRC
 
File_Handling in C.ppt
lakshmanarao027MVGRC
 
EASY UNDERSTANDING OF FILES IN C LANGUAGE.pdf
sudhakargeruganti
 
MODULE 8-File and preprocessor.pptx for c program learners easy learning
a50905877
 
File in c
Prabhu Govind
 
File management
sumathiv9
 
File management
AnishaThakkar2
 
Mesics lecture files in 'c'
eShikshak
 
Concept of file handling in c
MugdhaSharma11
 
File handling in c
David Livingston J
 
Unit5
mrecedu
 
PPS PPT 2.pptx
Sandeepbhuma1
 
1file handling
Frijo Francis
 
file_handling_in_c.ppt
yuvrajkeshri
 
637225560972186380.pdf
SureshKalirawna
 
Unit5 C
arnold 7490
 

More from 10300PEDDIKISHOR (7)

PPT
c-Functions power point presentation on c functions
10300PEDDIKISHOR
 
PPT
c-step-by-step-execution power point presentation
10300PEDDIKISHOR
 
PPT
Structures-in-C programming with examples
10300PEDDIKISHOR
 
PPT
Unity JDBC ICEIS ppt UnityJDBC ICEIS ppt
10300PEDDIKISHOR
 
PPT
JDBC DriversPros and Cons of Each Driver
10300PEDDIKISHOR
 
PPT
Java Database Connectivity Java Database
10300PEDDIKISHOR
 
PDF
Every SQL Query must have: • SELECT clause: specifies columns to be retained ...
10300PEDDIKISHOR
 
c-Functions power point presentation on c functions
10300PEDDIKISHOR
 
c-step-by-step-execution power point presentation
10300PEDDIKISHOR
 
Structures-in-C programming with examples
10300PEDDIKISHOR
 
Unity JDBC ICEIS ppt UnityJDBC ICEIS ppt
10300PEDDIKISHOR
 
JDBC DriversPros and Cons of Each Driver
10300PEDDIKISHOR
 
Java Database Connectivity Java Database
10300PEDDIKISHOR
 
Every SQL Query must have: • SELECT clause: specifies columns to be retained ...
10300PEDDIKISHOR
 
Ad

Recently uploaded (20)

PPTX
2025 Completing the Pre-SET Plan Form.pptx
mansk2
 
PDF
THE PSYCHOANALYTIC OF THE BLACK CAT BY EDGAR ALLAN POE (1).pdf
nabilahk908
 
PDF
Gladiolous Cultivation practices by AKL.pdf
kushallamichhame
 
PDF
English 3 Quarter 1_LEwithLAS_Week 1.pdf
DeAsisAlyanajaneH
 
PPTX
F-BLOCK ELEMENTS POWER POINT PRESENTATIONS
mprpgcwa2024
 
PPTX
A Visual Introduction to the Prophet Jeremiah
Steve Thomason
 
PDF
Public Health For The 21st Century 1st Edition Judy Orme Jane Powell
trjnesjnqg7801
 
PPTX
Wage and Salary Computation.ppt.......,x
JosalitoPalacio
 
PDF
K12 Tableau User Group virtual event June 18, 2025
dogden2
 
PDF
LDMMIA Shop & Student News Summer Solstice 25
LDM & Mia eStudios
 
PPTX
GREAT QUIZ EXCHANGE 2025 - GENERAL QUIZ.pptx
Ronisha Das
 
PDF
Hurricane Helene Application Documents Checklists
Mebane Rash
 
PPTX
Photo chemistry Power Point Presentation
mprpgcwa2024
 
PDF
Romanticism in Love and Sacrifice An Analysis of Oscar Wilde’s The Nightingal...
KaryanaTantri21
 
PPTX
June 2025 Progress Update With Board Call_In process.pptx
International Society of Service Innovation Professionals
 
PPTX
How to Add New Item in CogMenu in Odoo 18
Celine George
 
PPTX
YSPH VMOC Special Report - Measles Outbreak Southwest US 6-14-2025.pptx
Yale School of Public Health - The Virtual Medical Operations Center (VMOC)
 
PPTX
How to use search fetch method in Odoo 18
Celine George
 
PPTX
Pests of Maize: An comprehensive overview.pptx
Arshad Shaikh
 
PPTX
Values Education 10 Quarter 1 Module .pptx
JBPafin
 
2025 Completing the Pre-SET Plan Form.pptx
mansk2
 
THE PSYCHOANALYTIC OF THE BLACK CAT BY EDGAR ALLAN POE (1).pdf
nabilahk908
 
Gladiolous Cultivation practices by AKL.pdf
kushallamichhame
 
English 3 Quarter 1_LEwithLAS_Week 1.pdf
DeAsisAlyanajaneH
 
F-BLOCK ELEMENTS POWER POINT PRESENTATIONS
mprpgcwa2024
 
A Visual Introduction to the Prophet Jeremiah
Steve Thomason
 
Public Health For The 21st Century 1st Edition Judy Orme Jane Powell
trjnesjnqg7801
 
Wage and Salary Computation.ppt.......,x
JosalitoPalacio
 
K12 Tableau User Group virtual event June 18, 2025
dogden2
 
LDMMIA Shop & Student News Summer Solstice 25
LDM & Mia eStudios
 
GREAT QUIZ EXCHANGE 2025 - GENERAL QUIZ.pptx
Ronisha Das
 
Hurricane Helene Application Documents Checklists
Mebane Rash
 
Photo chemistry Power Point Presentation
mprpgcwa2024
 
Romanticism in Love and Sacrifice An Analysis of Oscar Wilde’s The Nightingal...
KaryanaTantri21
 
June 2025 Progress Update With Board Call_In process.pptx
International Society of Service Innovation Professionals
 
How to Add New Item in CogMenu in Odoo 18
Celine George
 
YSPH VMOC Special Report - Measles Outbreak Southwest US 6-14-2025.pptx
Yale School of Public Health - The Virtual Medical Operations Center (VMOC)
 
How to use search fetch method in Odoo 18
Celine George
 
Pests of Maize: An comprehensive overview.pptx
Arshad Shaikh
 
Values Education 10 Quarter 1 Module .pptx
JBPafin
 
Ad

file handling in c programming with file functions

  • 2. What is a File? • A file is a collection of related data that a computers treats as a single unit. • Computers store files to secondary storage so that the contents of files remain intact when a computer shuts down. • When a computer reads a file, it copies the file from the storage device to memory; when it writes to a file, it transfers data from memory to the storage device. • C uses a structure called FILE (defined in stdio.h) to store the attributes of a file.
  • 3. Steps in Processing a File 1. Create the stream via a pointer variable using the FILE structure: FILE *p; 2. Open the file, associating the stream name with the file name. 3. Read or write the data. 4. Close the file.
  • 4. The basic file operations are • fopen - open a file- specify how its opened (read/write) and type (binary/text) • fclose - close an opened file • fread - read from a file • fwrite - write to a file • fseek/fsetpos - move a file pointer to somewhere in a file. • ftell/fgetpos - tell you where the file pointer is located.
  • 5. File Open Modes from Table 7-1 in Forouzan & Gilberg, p. 400
  • 6. More on File Open Modes from Figure 7-4 in Forouzan & Gilberg, p. 401
  • 7. Additionally, • r+ - open for reading and writing, start at beginning • w+ - open for reading and writing (overwrite file) • a+ - open for reading and writing (append if file exists)
  • 8. File Open • The file open function (fopen) serves two purposes: – It makes the connection between the physical file and the stream. – It creates “a program file structure to store the information” C needs to process the file. • Syntax: filepointer=fopen(“filename”, “mode”);
  • 9. More On fopen • The file mode tells C how the program will use the file. • The filename indicates the system name and location for the file. • We assign the return value of fopen to our pointer variable: spData = fopen(“MYFILE.TXT”, “w”); spData = fopen(“A:MYFILE.TXT”, “w”);
  • 10. More On fopen from Figure 7-3 in Forouzan & Gilberg, p. 399
  • 11. Closing a File • When we finish with a mode, we need to close the file before ending the program or beginning another mode with that same file. • To close a file, we use fclose and the pointer variable: fclose(spData);
  • 12. fprintf() Syntax: fprintf (fp,"string",variables); Example: int i = 12; float x = 2.356; char ch = 's'; FILE *fp; fp=fopen(“out.txt”,”w”); fprintf (fp, "%d %f %c", i, x, ch);
  • 14. getc() Syntax: identifier = getc (file pointer); Example: FILE *fp; fp=fopen(“input.txt”,”r”); char ch; ch = getc (fp);
  • 15. putc() write a single character to the output file, pointed to by fp. Example: FILE *fp; char ch; putc (ch,fp);
  • 16. End of File • There are a number of ways to test for the end-of-file condition. Another way is to use the value returned by the fscanf function: FILE *fptr1; int istatus ; istatus = fscanf (fptr1, "%d", &var) ; if ( istatus == feof(fptr1) ) { printf ("End-of-file encountered.n”) ; }
  • 17. Reading and Writing Files #include <stdio.h> int main ( ) { FILE *outfile, *infile ; int b = 5, f ; float a = 13.72, c = 6.68, e, g ; outfile = fopen ("testdata", "w") ; fprintf (outfile, “ %f %d %f ", a, b, c) ; fclose (outfile) ; infile = fopen ("testdata", "r") ; fscanf (infile,"%f %d %f", &e, &f, &g) ; printf (“ %f %d %f n ", a, b, c) ; printf (“ %f %d %f n ", e, f, g) ; }
  • 18. Example #include <stdio.h> #include<conio.h> void main() { char ch; FILE *fp; fp=fopen("out.txt","r"); while(!feof(fp)) { ch=getc(fp); printf("n%c",ch); } getch(); }
  • 19. fread () Declaration: size_t fread(void *ptr, size_t size, size_t n, FILE *stream); Remarks: fread reads a specified number of equal-sized data items from an input stream into a block. ptr = Points to a block into which data is read size = Length of each item read, in bytes n = Number of items read stream = file pointer
  • 20. Example Example: #include <stdio.h> int main() { FILE *f; char buffer[11]; if (f = fopen("fred.txt", “r”)) { fread(buffer, 1, 10, f); buffer[10] = 0; fclose(f); printf("first 10 characters of the file:n%sn", buffer); } return 0; }
  • 21. fwrite() Declaration: size_t fwrite(const void *ptr, size_t size, size_t n, FILE*stream); Remarks: fwrite appends a specified number of equal-sized data items to an output file. ptr = Pointer to any object; the data written begins at ptr size = Length of each item of data n =Number of data items to be appended stream = file pointer
  • 22. Example Example: #include <stdio.h> int main() { char a[10]={'1','2','3','4','5','6','7','8','9','a'}; FILE *fs; fs=fopen("Project.txt","w"); fwrite(a,1,10,fs); fclose(fs); return 0; }
  • 23. fseek() This function sets the file position indicator for the stream pointed to by stream or you can say it seeks a specified place within a file and modify it. SEEK_SET Seeks from beginning of file SEEK_CUR Seeks from current position SEEK_END Seeks from end of file Example: #include <stdio.h> int main() { FILE * f; f = fopen("myfile.txt", "w"); fputs("Hello World", f); fseek(f, 6, SEEK_SET); SEEK_CUR, SEEK_END fputs(" India", f); fclose(f); return 0; }
  • 24. ftell() offset = ftell( file pointer ); "ftell" returns the current position for input or output on the file #include <stdio.h> int main(void) { FILE *stream; stream = fopen("MYFILE.TXT", "w"); fprintf(stream, "This is a test"); printf("The file pointer is at byte %ldn", ftell(stream)); fclose(stream); return 0; }