Module 03 File Handling in C

Tushar B Kute
Tushar B KuteResearcher at http://mitu.co.in
See through C
Module 3
File Handling
Tushar B Kute
http://tusharkute.com
What is a File?What is a File?
●
AA filefile is a collection of related data that ais a collection of related data that a
computers treats as a single unit.computers treats as a single unit.
●
Computers store files to secondary storage soComputers store files to secondary storage so
that the contents of files remain intact when athat the contents of files remain intact when a
computer shuts down.computer shuts down.
●
When a computer reads a file, it copies the fileWhen a computer reads a file, it copies the file
from the storage device to memory; when itfrom the storage device to memory; when it
writes to a file, it transfers data from memory towrites to a file, it transfers data from memory to
the storage device.the storage device.
●
C uses a structure calledC uses a structure called FILEFILE (defined in(defined in
stdio.hstdio.h) to store the attributes of a file.) to store the attributes of a file.
Steps in Processing a FileSteps in Processing a File
1.1. Create the stream via a pointer variable using theCreate the stream via a pointer variable using the FILEFILE
structure:structure:
FILE *p;FILE *p;
2.2. Open the file, associating the stream name with the fileOpen the file, associating the stream name with the file
name.name.
3.3. Read or write the data.Read or write the data.
4.4. Close the file.Close the file.
The basic file operations areThe basic file operations are
●
fopen - open a file- specify how its openedfopen - open a file- specify how its opened
(read/write) and type (binary/text)(read/write) and type (binary/text)
●
fclose - close an opened filefclose - close an opened file
●
fread - read from a filefread - read from a file
●
fwrite - write to a filefwrite - write to a file
●
fseek/fsetpos - move a file pointer tofseek/fsetpos - move a file pointer to
somewhere in a file.somewhere in a file.
●
ftell/fgetpos - tell you where the file pointer isftell/fgetpos - tell you where the file pointer is
located.located.
File Open ModesFile Open Modes
More on File Open ModesMore on File Open Modes
Additionally,Additionally,
●
r+ - open for reading and writing, start at beginningr+ - open for reading and writing, start at beginning
●
w+ - open for reading and writing (overwrite file)w+ - open for reading and writing (overwrite file)
●
a+ - open for reading and writing (append if file exists)a+ - open for reading and writing (append if file exists)
File OpenFile Open
●
The file open function (The file open function (fopenfopen) serves two purposes:) serves two purposes:
– It makes the connection between the physical file andIt makes the connection between the physical file and
the stream.the stream.
– It creates “a program file structure to store theIt creates “a program file structure to store the
information” C needs to process the file.information” C needs to process the file.
●
Syntax:Syntax:
filepointer=filepointer=fopen(“filename”, “mode”);fopen(“filename”, “mode”);
More OnMore On fopenfopen
●
The file mode tells C how the program willThe file mode tells C how the program will
use the file.use the file.
●
The filename indicates the system nameThe filename indicates the system name
and location for the file.and location for the file.
●
We assign the return value ofWe assign the return value of fopenfopen to ourto our
pointer variable:pointer variable:
spData = fopen(“MYFILE.TXT”, “w”);spData = fopen(“MYFILE.TXT”, “w”);
spData = fopen(“A:MYFILE.TXT”, “w”);spData = fopen(“A:MYFILE.TXT”, “w”);
More OnMore On fopenfopen
Closing a FileClosing a File
●
When we finish with a mode, we need to close the fileWhen we finish with a mode, we need to close the file
before ending the program or beginning another modebefore ending the program or beginning another mode
with that same file.with that same file.
●
To close a file, we useTo close a file, we use fclosefclose and the pointer variable:and the pointer variable:
fclose(spData);fclose(spData);
fprintf()fprintf()
Syntax:Syntax:
fprintf (fp,"string",variables);fprintf (fp,"string",variables);
Example:Example:
int i = 12;int i = 12;
float x = 2.356;float x = 2.356;
char ch = 's';char ch = 's';
FILE *fp;FILE *fp;
fp=fopen(“out.txt”,”w”);fp=fopen(“out.txt”,”w”);
fprintf (fp, "%d %f %c", i, x,fprintf (fp, "%d %f %c", i, x, ch);ch);
fscanf()fscanf()
Syntax:Syntax:
fscanf (fp,"string",identifiers);fscanf (fp,"string",identifiers);
Example:Example:
FILE *fp;FILE *fp;
fp=fopen(“input.txt”,”r”);fp=fopen(“input.txt”,”r”);
int i;int i;
fscanf (fp,“%d",&i);fscanf (fp,“%d",&i);
fgetc()fgetc()
Syntax:Syntax:
identifier = fgetc (file pointer);identifier = fgetc (file pointer);
Example:Example:
FILE *fp;FILE *fp;
fp=fopen(“input.txt”,”r”);fp=fopen(“input.txt”,”r”);
char ch;char ch;
ch = fgetc (fp);ch = fgetc (fp);
fputc()fputc()
write a single character to the output file, pointed to by fp.write a single character to the output file, pointed to by fp.
Example:Example:
FILE *fp;FILE *fp;
char ch;char ch;
fputc (ch,fp);fputc (ch,fp);
End of FileEnd of File
●
There are a number of ways to test for the end-of-fileThere are a number of ways to test for the end-of-file
condition. Another way is to use the value returned bycondition. Another way is to use the value returned by
thethe fscanffscanf function:function:
FILE *fptr1;FILE *fptr1;
int istatus ;int istatus ;
istatus = fscanf (fptr1, "%d", &var) ;istatus = fscanf (fptr1, "%d", &var) ;
if ( istatus == feof(fptr1) )if ( istatus == feof(fptr1) )
{{
printf ("End-of-file encountered.n”) ;printf ("End-of-file encountered.n”) ;
}}
Reading and Writing FilesReading and Writing Files
#include <stdio.h>#include <stdio.h>
int main ( )int main ( )
{{
FILE *outfile, *infile ;FILE *outfile, *infile ;
int b = 5, f ;int b = 5, f ;
float a = 13.72, c = 6.68, e, g ;float a = 13.72, c = 6.68, e, g ;
outfile = fopen ("testdata", "w") ;outfile = fopen ("testdata", "w") ;
fprintf (outfile, “ %f %d %f ", a, b, c) ;fprintf (outfile, “ %f %d %f ", a, b, c) ;
fclose (outfile) ;fclose (outfile) ;
infile = fopen ("testdata", "r") ;infile = fopen ("testdata", "r") ;
fscanf (infile,"%f %d %f", &e, &f, &g) ;fscanf (infile,"%f %d %f", &e, &f, &g) ;
printf (“ %f %d %f n ", a, b, c) ;printf (“ %f %d %f n ", a, b, c) ;
printf (“ %f %d %f n ", e, f, g) ;printf (“ %f %d %f n ", e, f, g) ;
}}
ExampleExample
#include <stdio.h>#include <stdio.h>
#include<conio.h>#include<conio.h>
int main()int main()
{{
char ch;char ch;
FILE *fp;FILE *fp;
fp=fopen("out.txt","r");fp=fopen("out.txt","r");
while(!feof(fp))while(!feof(fp))
{{
ch=getc(fp);ch=getc(fp);
printf("n%c",ch);printf("n%c",ch);
}}
fcloseall( );fcloseall( );
}}
freadfread ()()
Declaration:Declaration:
size_t fread(void *ptr, size_t size, size_t n, FILE *stream);size_t fread(void *ptr, size_t size, size_t n, FILE *stream);
Remarks:Remarks:
fread reads a specified number of equal-sizedfread reads a specified number of equal-sized
data items from an input stream into a block.data items from an input stream into a block.
ptr = Points to a block into which data is readptr = Points to a block into which data is read
size = Length of each item read, in bytessize = Length of each item read, in bytes
n = Number of items readn = Number of items read
stream = file pointerstream = file pointer
ExampleExample
Example:Example:
#include <stdio.h>#include <stdio.h>
int main()int main()
{{
FILE *f;FILE *f;
char buffer[11];char buffer[11];
if (f = fopen("fred.txt", “r”))if (f = fopen("fred.txt", “r”))
{{
fread(buffer, 1, 10, f);fread(buffer, 1, 10, f);
buffer[10] = 0;buffer[10] = 0;
fclose(f);fclose(f);
printf("first 10 characters of the file:n%sn", buffer);printf("first 10 characters of the file:n%sn", buffer);
}}
return 0;return 0;
}}
fwrite()fwrite()
Declaration:Declaration:
size_t fwrite(const void *ptr, size_t size, size_t n, FILE*stream);size_t fwrite(const void *ptr, size_t size, size_t n, FILE*stream);
Remarks:Remarks:
fwrite appends a specified number of equal-sized data items to anfwrite appends a specified number of equal-sized data items to an
output file.output file.
ptr = Pointer to any object; the data written begins at ptrptr = Pointer to any object; the data written begins at ptr
size = Length of each item of datasize = Length of each item of data
n =Number of data items to be appendedn =Number of data items to be appended
stream = file pointerstream = file pointer
ExampleExample
Example:Example:
#include <stdio.h>#include <stdio.h>
int main()int main()
{{
char a[10]={'1','2','3','4','5','6','7','8','9','a'};char a[10]={'1','2','3','4','5','6','7','8','9','a'};
FILE *fs;FILE *fs;
fs=fopen("Project.txt","w");fs=fopen("Project.txt","w");
fwrite(a,1,10,fs);fwrite(a,1,10,fs);
fclose(fs);fclose(fs);
return 0;return 0;
}}
fseek()fseek()
This function sets the file position indicator for the stream pointed to by streamThis 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.or you can say it seeks a specified place within a file and modify it.
SEEK_SETSEEK_SET Seeks from beginning of fileSeeks from beginning of file
SEEK_CURSEEK_CUR Seeks from current positionSeeks from current position
SEEK_ENDSEEK_END Seeks from end of fileSeeks from end of file
Example:Example:
#include#include <stdio.h><stdio.h>
intint mainmain()()
{{
FILE * f;FILE * f;
f = fopen("myfile.txt", "w");f = fopen("myfile.txt", "w");
fputs("Hello World", f);fputs("Hello World", f);
fseek(f, 6, SEEK_SET); SEEK_CUR, SEEK_ENDfseek(f, 6, SEEK_SET); SEEK_CUR, SEEK_END
fputs(" India", f);fputs(" India", f);
fclose(f);fclose(f);
returnreturn 0;0;
}}
ftell()ftell()
offset = ftell( file pointer );offset = ftell( file pointer );
"ftell" returns the current position for input or output on the file"ftell" returns the current position for input or output on the file
#include <stdio.h>#include <stdio.h>
int main(void)int main(void)
{{
FILE *stream;FILE *stream;
stream = fopen("MYFILE.TXT", "w");stream = fopen("MYFILE.TXT", "w");
fprintf(stream, "This is a test");fprintf(stream, "This is a test");
printf("The file pointer is at byte %ldn", ftell(stream));printf("The file pointer is at byte %ldn", ftell(stream));
fclose(stream);fclose(stream);
return 0;return 0;
}}
Thank you
This presentation is created using LibreOffice Impress 3.6.2.2
1 of 25

Recommended

File handling in 'C' by
File handling in 'C'File handling in 'C'
File handling in 'C'Gaurav Garg
2.8K views32 slides
File handling in c by
File handling in cFile handling in c
File handling in cmohit biswal
433 views29 slides
C programming file handling by
C  programming file handlingC  programming file handling
C programming file handlingargusacademy
1.3K views10 slides
File handling in c by
File  handling in cFile  handling in c
File handling in cthirumalaikumar3
587 views34 slides
File in c by
File in cFile in c
File in cPrabhu Govind
1.9K views10 slides

More Related Content

What's hot

File handling in c by
File handling in c File handling in c
File handling in c Vikash Dhal
5.1K views25 slides
File in C language by
File in C languageFile in C language
File in C languageManash Kumar Mondal
909 views41 slides
File in C Programming by
File in C ProgrammingFile in C Programming
File in C ProgrammingSonya Akter Rupa
5.4K views11 slides
File handling-dutt by
File handling-duttFile handling-dutt
File handling-duttAnil Dutt
634 views23 slides
File handling-c programming language by
File handling-c programming languageFile handling-c programming language
File handling-c programming languagethirumalaikumar3
1K views26 slides
File handling-c by
File handling-cFile handling-c
File handling-cCGC Technical campus,Mohali
1.8K views44 slides

What's hot(20)

File handling in c by Vikash Dhal
File handling in c File handling in c
File handling in c
Vikash Dhal5.1K views
File handling-dutt by Anil Dutt
File handling-duttFile handling-dutt
File handling-dutt
Anil Dutt634 views
Understanding c file handling functions with examples by Muhammed Thanveer M
Understanding c file handling functions with examplesUnderstanding c file handling functions with examples
Understanding c file handling functions with examples
File handling in C by Rabin BK
File handling in CFile handling in C
File handling in C
Rabin BK114 views
File handling in C by Faixan by ٖFaiXy :)
File handling in C by FaixanFile handling in C by Faixan
File handling in C by Faixan
ٖFaiXy :)1.1K views
File handling in c by aakanksha s
File handling in cFile handling in c
File handling in c
aakanksha s9.3K views
Unit5 by mrecedu
Unit5Unit5
Unit5
mrecedu521 views
Files in C by Prabu U
Files in CFiles in C
Files in C
Prabu U422 views

Viewers also liked

UNIT 10. Files and file handling in C by
UNIT 10. Files and file handling in CUNIT 10. Files and file handling in C
UNIT 10. Files and file handling in CAshim Lamichhane
9.6K views34 slides
All important c programby makhan kumbhkar by
All important c programby makhan kumbhkarAll important c programby makhan kumbhkar
All important c programby makhan kumbhkarsandeep kumbhkar
1K views34 slides
week-20x by
week-20xweek-20x
week-20xKITE www.kitecolleges.com
308 views6 slides
Input Output Management In C Programming by
Input Output Management In C ProgrammingInput Output Management In C Programming
Input Output Management In C ProgrammingKamal Acharya
3.9K views17 slides
C programming language by
C programming languageC programming language
C programming languageAbin Rimal
1K views29 slides
Palindrome number program in c by
Palindrome number program in cPalindrome number program in c
Palindrome number program in cmohdshanu
1K views2 slides

Viewers also liked(18)

UNIT 10. Files and file handling in C by Ashim Lamichhane
UNIT 10. Files and file handling in CUNIT 10. Files and file handling in C
UNIT 10. Files and file handling in C
Ashim Lamichhane9.6K views
All important c programby makhan kumbhkar by sandeep kumbhkar
All important c programby makhan kumbhkarAll important c programby makhan kumbhkar
All important c programby makhan kumbhkar
sandeep kumbhkar1K views
Input Output Management In C Programming by Kamal Acharya
Input Output Management In C ProgrammingInput Output Management In C Programming
Input Output Management In C Programming
Kamal Acharya3.9K views
C programming language by Abin Rimal
C programming languageC programming language
C programming language
Abin Rimal1K views
Palindrome number program in c by mohdshanu
Palindrome number program in cPalindrome number program in c
Palindrome number program in c
mohdshanu1K views
Pointers and call by value, reference, address in C by Syed Mustafa
Pointers and call by value, reference, address in CPointers and call by value, reference, address in C
Pointers and call by value, reference, address in C
Syed Mustafa4.9K views
Managing input and output operation in c by yazad dumasia
Managing input and output operation in cManaging input and output operation in c
Managing input and output operation in c
yazad dumasia6.6K views
Mesics lecture 5 input – output in ‘c’ by eShikshak
Mesics lecture 5   input – output in ‘c’Mesics lecture 5   input – output in ‘c’
Mesics lecture 5 input – output in ‘c’
eShikshak5.2K views
C programs by Minu S
C programsC programs
C programs
Minu S8.5K views
file handling c++ by Guddu Spy
file handling c++file handling c++
file handling c++
Guddu Spy47.9K views
File Management Presentation by SgtMasterGunz
File Management PresentationFile Management Presentation
File Management Presentation
SgtMasterGunz6.8K views
Introduction to CSS by Amit Tyagi
Introduction to CSSIntroduction to CSS
Introduction to CSS
Amit Tyagi45.3K views

Similar to Module 03 File Handling in C

File management by
File managementFile management
File managementlalithambiga kamaraj
333 views33 slides
Lecture 20 - File Handling by
Lecture 20 - File HandlingLecture 20 - File Handling
Lecture 20 - File HandlingMd. Imran Hossain Showrov
69 views23 slides
Data Structure Using C - FILES by
Data Structure Using C - FILESData Structure Using C - FILES
Data Structure Using C - FILESHarish Kamat
59 views43 slides
File handling by
File handlingFile handling
File handlingAns Ali
107 views25 slides
file_handling_in_c.ppt by
file_handling_in_c.pptfile_handling_in_c.ppt
file_handling_in_c.pptyuvrajkeshri
3 views25 slides
Unit5 C by
Unit5 C Unit5 C
Unit5 C arnold 7490
1.2K views16 slides

Similar to Module 03 File Handling in C(20)

Data Structure Using C - FILES by Harish Kamat
Data Structure Using C - FILESData Structure Using C - FILES
Data Structure Using C - FILES
Harish Kamat59 views
File handling by Ans Ali
File handlingFile handling
File handling
Ans Ali107 views
EASY UNDERSTANDING OF FILES IN C LANGUAGE.pdf by sudhakargeruganti
EASY UNDERSTANDING OF FILES IN C LANGUAGE.pdfEASY UNDERSTANDING OF FILES IN C LANGUAGE.pdf
EASY UNDERSTANDING OF FILES IN C LANGUAGE.pdf
File management by sumathiv9
File managementFile management
File management
sumathiv9109 views
Mesics lecture files in 'c' by eShikshak
Mesics lecture   files in 'c'Mesics lecture   files in 'c'
Mesics lecture files in 'c'
eShikshak2.6K views
file handling1 by student
file handling1file handling1
file handling1
student765 views
File handling With Solve Programs by Rohan Gajre
File handling With Solve ProgramsFile handling With Solve Programs
File handling With Solve Programs
Rohan Gajre364 views

More from Tushar B Kute

Apache Pig: A big data processor by
Apache Pig: A big data processorApache Pig: A big data processor
Apache Pig: A big data processorTushar B Kute
3.2K views50 slides
01 Introduction to Android by
01 Introduction to Android01 Introduction to Android
01 Introduction to AndroidTushar B Kute
868 views15 slides
Ubuntu OS and it's Flavours by
Ubuntu OS and it's FlavoursUbuntu OS and it's Flavours
Ubuntu OS and it's FlavoursTushar B Kute
1.7K views34 slides
Install Drupal in Ubuntu by Tushar B. Kute by
Install Drupal in Ubuntu by Tushar B. KuteInstall Drupal in Ubuntu by Tushar B. Kute
Install Drupal in Ubuntu by Tushar B. KuteTushar B Kute
893 views25 slides
Install Wordpress in Ubuntu Linux by Tushar B. Kute by
Install Wordpress in Ubuntu Linux by Tushar B. KuteInstall Wordpress in Ubuntu Linux by Tushar B. Kute
Install Wordpress in Ubuntu Linux by Tushar B. KuteTushar B Kute
739 views26 slides
Share File easily between computers using sftp by
Share File easily between computers using sftpShare File easily between computers using sftp
Share File easily between computers using sftpTushar B Kute
2.2K views29 slides

More from Tushar B Kute(20)

Apache Pig: A big data processor by Tushar B Kute
Apache Pig: A big data processorApache Pig: A big data processor
Apache Pig: A big data processor
Tushar B Kute3.2K views
01 Introduction to Android by Tushar B Kute
01 Introduction to Android01 Introduction to Android
01 Introduction to Android
Tushar B Kute868 views
Ubuntu OS and it's Flavours by Tushar B Kute
Ubuntu OS and it's FlavoursUbuntu OS and it's Flavours
Ubuntu OS and it's Flavours
Tushar B Kute1.7K views
Install Drupal in Ubuntu by Tushar B. Kute by Tushar B Kute
Install Drupal in Ubuntu by Tushar B. KuteInstall Drupal in Ubuntu by Tushar B. Kute
Install Drupal in Ubuntu by Tushar B. Kute
Tushar B Kute893 views
Install Wordpress in Ubuntu Linux by Tushar B. Kute by Tushar B Kute
Install Wordpress in Ubuntu Linux by Tushar B. KuteInstall Wordpress in Ubuntu Linux by Tushar B. Kute
Install Wordpress in Ubuntu Linux by Tushar B. Kute
Tushar B Kute739 views
Share File easily between computers using sftp by Tushar B Kute
Share File easily between computers using sftpShare File easily between computers using sftp
Share File easily between computers using sftp
Tushar B Kute2.2K views
Signal Handling in Linux by Tushar B Kute
Signal Handling in LinuxSignal Handling in Linux
Signal Handling in Linux
Tushar B Kute10.4K views
Implementation of FIFO in Linux by Tushar B Kute
Implementation of FIFO in LinuxImplementation of FIFO in Linux
Implementation of FIFO in Linux
Tushar B Kute3.3K views
Implementation of Pipe in Linux by Tushar B Kute
Implementation of Pipe in LinuxImplementation of Pipe in Linux
Implementation of Pipe in Linux
Tushar B Kute5.2K views
Basic Multithreading using Posix Threads by Tushar B Kute
Basic Multithreading using Posix ThreadsBasic Multithreading using Posix Threads
Basic Multithreading using Posix Threads
Tushar B Kute1.5K views
Part 04 Creating a System Call in Linux by Tushar B Kute
Part 04 Creating a System Call in LinuxPart 04 Creating a System Call in Linux
Part 04 Creating a System Call in Linux
Tushar B Kute3.8K views
Part 03 File System Implementation in Linux by Tushar B Kute
Part 03 File System Implementation in LinuxPart 03 File System Implementation in Linux
Part 03 File System Implementation in Linux
Tushar B Kute3.4K views
Part 02 Linux Kernel Module Programming by Tushar B Kute
Part 02 Linux Kernel Module ProgrammingPart 02 Linux Kernel Module Programming
Part 02 Linux Kernel Module Programming
Tushar B Kute3.6K views
Part 01 Linux Kernel Compilation (Ubuntu) by Tushar B Kute
Part 01 Linux Kernel Compilation (Ubuntu)Part 01 Linux Kernel Compilation (Ubuntu)
Part 01 Linux Kernel Compilation (Ubuntu)
Tushar B Kute3.7K views
Open source applications softwares by Tushar B Kute
Open source applications softwaresOpen source applications softwares
Open source applications softwares
Tushar B Kute1K views
Introduction to Ubuntu Edge Operating System (Ubuntu Touch) by Tushar B Kute
Introduction to Ubuntu Edge Operating System (Ubuntu Touch)Introduction to Ubuntu Edge Operating System (Ubuntu Touch)
Introduction to Ubuntu Edge Operating System (Ubuntu Touch)
Tushar B Kute5.6K views
Unit 6 Operating System TEIT Savitribai Phule Pune University by Tushar B Kute by Tushar B Kute
Unit 6 Operating System TEIT Savitribai Phule Pune University by Tushar B KuteUnit 6 Operating System TEIT Savitribai Phule Pune University by Tushar B Kute
Unit 6 Operating System TEIT Savitribai Phule Pune University by Tushar B Kute
Tushar B Kute3.9K views
Technical blog by Engineering Students of Sandip Foundation, itsitrc by Tushar B Kute
Technical blog by Engineering Students of Sandip Foundation, itsitrcTechnical blog by Engineering Students of Sandip Foundation, itsitrc
Technical blog by Engineering Students of Sandip Foundation, itsitrc
Tushar B Kute870 views
Chapter 01 Introduction to Java by Tushar B Kute by Tushar B Kute
Chapter 01 Introduction to Java by Tushar B KuteChapter 01 Introduction to Java by Tushar B Kute
Chapter 01 Introduction to Java by Tushar B Kute
Tushar B Kute3K views
Chapter 02: Classes Objects and Methods Java by Tushar B Kute by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B KuteChapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
Tushar B Kute8.4K views

Recently uploaded

2023-November-Schneider Electric-Meetup-BCN Admin Group.pptx by
2023-November-Schneider Electric-Meetup-BCN Admin Group.pptx2023-November-Schneider Electric-Meetup-BCN Admin Group.pptx
2023-November-Schneider Electric-Meetup-BCN Admin Group.pptxanimuscrm
14 views19 slides
Headless JS UG Presentation.pptx by
Headless JS UG Presentation.pptxHeadless JS UG Presentation.pptx
Headless JS UG Presentation.pptxJack Spektor
7 views24 slides
Keep by
KeepKeep
KeepGeniusee
75 views10 slides
Short_Story_PPT.pdf by
Short_Story_PPT.pdfShort_Story_PPT.pdf
Short_Story_PPT.pdfutkarshsatishkumarsh
5 views16 slides
Programming Field by
Programming FieldProgramming Field
Programming Fieldthehardtechnology
5 views9 slides
DSD-INT 2023 European Digital Twin Ocean and Delft3D FM - Dols by
DSD-INT 2023 European Digital Twin Ocean and Delft3D FM - DolsDSD-INT 2023 European Digital Twin Ocean and Delft3D FM - Dols
DSD-INT 2023 European Digital Twin Ocean and Delft3D FM - DolsDeltares
7 views23 slides

Recently uploaded(20)

2023-November-Schneider Electric-Meetup-BCN Admin Group.pptx by animuscrm
2023-November-Schneider Electric-Meetup-BCN Admin Group.pptx2023-November-Schneider Electric-Meetup-BCN Admin Group.pptx
2023-November-Schneider Electric-Meetup-BCN Admin Group.pptx
animuscrm14 views
Headless JS UG Presentation.pptx by Jack Spektor
Headless JS UG Presentation.pptxHeadless JS UG Presentation.pptx
Headless JS UG Presentation.pptx
Jack Spektor7 views
DSD-INT 2023 European Digital Twin Ocean and Delft3D FM - Dols by Deltares
DSD-INT 2023 European Digital Twin Ocean and Delft3D FM - DolsDSD-INT 2023 European Digital Twin Ocean and Delft3D FM - Dols
DSD-INT 2023 European Digital Twin Ocean and Delft3D FM - Dols
Deltares7 views
Sprint 226 by ManageIQ
Sprint 226Sprint 226
Sprint 226
ManageIQ5 views
Quality Engineer: A Day in the Life by John Valentino
Quality Engineer: A Day in the LifeQuality Engineer: A Day in the Life
Quality Engineer: A Day in the Life
John Valentino6 views
FIMA 2023 Neo4j & FS - Entity Resolution.pptx by Neo4j
FIMA 2023 Neo4j & FS - Entity Resolution.pptxFIMA 2023 Neo4j & FS - Entity Resolution.pptx
FIMA 2023 Neo4j & FS - Entity Resolution.pptx
Neo4j7 views
Airline Booking Software by SharmiMehta
Airline Booking SoftwareAirline Booking Software
Airline Booking Software
SharmiMehta6 views
Navigating container technology for enhanced security by Niklas Saari by Metosin Oy
Navigating container technology for enhanced security by Niklas SaariNavigating container technology for enhanced security by Niklas Saari
Navigating container technology for enhanced security by Niklas Saari
Metosin Oy14 views
Advanced API Mocking Techniques by Dimpy Adhikary
Advanced API Mocking TechniquesAdvanced API Mocking Techniques
Advanced API Mocking Techniques
Dimpy Adhikary19 views
360 graden fabriek by info33492
360 graden fabriek360 graden fabriek
360 graden fabriek
info3349238 views
DSD-INT 2023 Delft3D FM Suite 2024.01 1D2D - Beta testing programme - Geertsema by Deltares
DSD-INT 2023 Delft3D FM Suite 2024.01 1D2D - Beta testing programme - GeertsemaDSD-INT 2023 Delft3D FM Suite 2024.01 1D2D - Beta testing programme - Geertsema
DSD-INT 2023 Delft3D FM Suite 2024.01 1D2D - Beta testing programme - Geertsema
Deltares17 views
Gen Apps on Google Cloud PaLM2 and Codey APIs in Action by Márton Kodok
Gen Apps on Google Cloud PaLM2 and Codey APIs in ActionGen Apps on Google Cloud PaLM2 and Codey APIs in Action
Gen Apps on Google Cloud PaLM2 and Codey APIs in Action
Márton Kodok5 views
Myths and Facts About Hospice Care: Busting Common Misconceptions by Care Coordinations
Myths and Facts About Hospice Care: Busting Common MisconceptionsMyths and Facts About Hospice Care: Busting Common Misconceptions
Myths and Facts About Hospice Care: Busting Common Misconceptions
Unmasking the Dark Art of Vectored Exception Handling: Bypassing XDR and EDR ... by Donato Onofri
Unmasking the Dark Art of Vectored Exception Handling: Bypassing XDR and EDR ...Unmasking the Dark Art of Vectored Exception Handling: Bypassing XDR and EDR ...
Unmasking the Dark Art of Vectored Exception Handling: Bypassing XDR and EDR ...
Donato Onofri825 views
AI and Ml presentation .pptx by FayazAli87
AI and Ml presentation .pptxAI and Ml presentation .pptx
AI and Ml presentation .pptx
FayazAli8711 views
DSD-INT 2023 Simulating a falling apron in Delft3D 4 - Engineering Practice -... by Deltares
DSD-INT 2023 Simulating a falling apron in Delft3D 4 - Engineering Practice -...DSD-INT 2023 Simulating a falling apron in Delft3D 4 - Engineering Practice -...
DSD-INT 2023 Simulating a falling apron in Delft3D 4 - Engineering Practice -...
Deltares6 views

Module 03 File Handling in C

  • 1. See through C Module 3 File Handling Tushar B Kute http://tusharkute.com
  • 2. What is a File?What is a File? ● AA filefile is a collection of related data that ais a collection of related data that a computers treats as a single unit.computers treats as a single unit. ● Computers store files to secondary storage soComputers store files to secondary storage so that the contents of files remain intact when athat the contents of files remain intact when a computer shuts down.computer shuts down. ● When a computer reads a file, it copies the fileWhen a computer reads a file, it copies the file from the storage device to memory; when itfrom the storage device to memory; when it writes to a file, it transfers data from memory towrites to a file, it transfers data from memory to the storage device.the storage device. ● C uses a structure calledC uses a structure called FILEFILE (defined in(defined in stdio.hstdio.h) to store the attributes of a file.) to store the attributes of a file.
  • 3. Steps in Processing a FileSteps in Processing a File 1.1. Create the stream via a pointer variable using theCreate the stream via a pointer variable using the FILEFILE structure:structure: FILE *p;FILE *p; 2.2. Open the file, associating the stream name with the fileOpen the file, associating the stream name with the file name.name. 3.3. Read or write the data.Read or write the data. 4.4. Close the file.Close the file.
  • 4. The basic file operations areThe basic file operations are ● fopen - open a file- specify how its openedfopen - open a file- specify how its opened (read/write) and type (binary/text)(read/write) and type (binary/text) ● fclose - close an opened filefclose - close an opened file ● fread - read from a filefread - read from a file ● fwrite - write to a filefwrite - write to a file ● fseek/fsetpos - move a file pointer tofseek/fsetpos - move a file pointer to somewhere in a file.somewhere in a file. ● ftell/fgetpos - tell you where the file pointer isftell/fgetpos - tell you where the file pointer is located.located.
  • 5. File Open ModesFile Open Modes
  • 6. More on File Open ModesMore on File Open Modes
  • 7. Additionally,Additionally, ● r+ - open for reading and writing, start at beginningr+ - open for reading and writing, start at beginning ● w+ - open for reading and writing (overwrite file)w+ - open for reading and writing (overwrite file) ● a+ - open for reading and writing (append if file exists)a+ - open for reading and writing (append if file exists)
  • 8. File OpenFile Open ● The file open function (The file open function (fopenfopen) serves two purposes:) serves two purposes: – It makes the connection between the physical file andIt makes the connection between the physical file and the stream.the stream. – It creates “a program file structure to store theIt creates “a program file structure to store the information” C needs to process the file.information” C needs to process the file. ● Syntax:Syntax: filepointer=filepointer=fopen(“filename”, “mode”);fopen(“filename”, “mode”);
  • 9. More OnMore On fopenfopen ● The file mode tells C how the program willThe file mode tells C how the program will use the file.use the file. ● The filename indicates the system nameThe filename indicates the system name and location for the file.and location for the file. ● We assign the return value ofWe assign the return value of fopenfopen to ourto our pointer variable:pointer variable: spData = fopen(“MYFILE.TXT”, “w”);spData = fopen(“MYFILE.TXT”, “w”); spData = fopen(“A:MYFILE.TXT”, “w”);spData = fopen(“A:MYFILE.TXT”, “w”);
  • 10. More OnMore On fopenfopen
  • 11. Closing a FileClosing a File ● When we finish with a mode, we need to close the fileWhen we finish with a mode, we need to close the file before ending the program or beginning another modebefore ending the program or beginning another mode with that same file.with that same file. ● To close a file, we useTo close a file, we use fclosefclose and the pointer variable:and the pointer variable: fclose(spData);fclose(spData);
  • 12. fprintf()fprintf() Syntax:Syntax: fprintf (fp,"string",variables);fprintf (fp,"string",variables); Example:Example: int i = 12;int i = 12; float x = 2.356;float x = 2.356; char ch = 's';char ch = 's'; FILE *fp;FILE *fp; fp=fopen(“out.txt”,”w”);fp=fopen(“out.txt”,”w”); fprintf (fp, "%d %f %c", i, x,fprintf (fp, "%d %f %c", i, x, ch);ch);
  • 13. fscanf()fscanf() Syntax:Syntax: fscanf (fp,"string",identifiers);fscanf (fp,"string",identifiers); Example:Example: FILE *fp;FILE *fp; fp=fopen(“input.txt”,”r”);fp=fopen(“input.txt”,”r”); int i;int i; fscanf (fp,“%d",&i);fscanf (fp,“%d",&i);
  • 14. fgetc()fgetc() Syntax:Syntax: identifier = fgetc (file pointer);identifier = fgetc (file pointer); Example:Example: FILE *fp;FILE *fp; fp=fopen(“input.txt”,”r”);fp=fopen(“input.txt”,”r”); char ch;char ch; ch = fgetc (fp);ch = fgetc (fp);
  • 15. fputc()fputc() write a single character to the output file, pointed to by fp.write a single character to the output file, pointed to by fp. Example:Example: FILE *fp;FILE *fp; char ch;char ch; fputc (ch,fp);fputc (ch,fp);
  • 16. End of FileEnd of File ● There are a number of ways to test for the end-of-fileThere are a number of ways to test for the end-of-file condition. Another way is to use the value returned bycondition. Another way is to use the value returned by thethe fscanffscanf function:function: FILE *fptr1;FILE *fptr1; int istatus ;int istatus ; istatus = fscanf (fptr1, "%d", &var) ;istatus = fscanf (fptr1, "%d", &var) ; if ( istatus == feof(fptr1) )if ( istatus == feof(fptr1) ) {{ printf ("End-of-file encountered.n”) ;printf ("End-of-file encountered.n”) ; }}
  • 17. Reading and Writing FilesReading and Writing Files #include <stdio.h>#include <stdio.h> int main ( )int main ( ) {{ FILE *outfile, *infile ;FILE *outfile, *infile ; int b = 5, f ;int b = 5, f ; float a = 13.72, c = 6.68, e, g ;float a = 13.72, c = 6.68, e, g ; outfile = fopen ("testdata", "w") ;outfile = fopen ("testdata", "w") ; fprintf (outfile, “ %f %d %f ", a, b, c) ;fprintf (outfile, “ %f %d %f ", a, b, c) ; fclose (outfile) ;fclose (outfile) ; infile = fopen ("testdata", "r") ;infile = fopen ("testdata", "r") ; fscanf (infile,"%f %d %f", &e, &f, &g) ;fscanf (infile,"%f %d %f", &e, &f, &g) ; printf (“ %f %d %f n ", a, b, c) ;printf (“ %f %d %f n ", a, b, c) ; printf (“ %f %d %f n ", e, f, g) ;printf (“ %f %d %f n ", e, f, g) ; }}
  • 18. ExampleExample #include <stdio.h>#include <stdio.h> #include<conio.h>#include<conio.h> int main()int main() {{ char ch;char ch; FILE *fp;FILE *fp; fp=fopen("out.txt","r");fp=fopen("out.txt","r"); while(!feof(fp))while(!feof(fp)) {{ ch=getc(fp);ch=getc(fp); printf("n%c",ch);printf("n%c",ch); }} fcloseall( );fcloseall( ); }}
  • 19. freadfread ()() Declaration:Declaration: size_t fread(void *ptr, size_t size, size_t n, FILE *stream);size_t fread(void *ptr, size_t size, size_t n, FILE *stream); Remarks:Remarks: fread reads a specified number of equal-sizedfread reads a specified number of equal-sized data items from an input stream into a block.data items from an input stream into a block. ptr = Points to a block into which data is readptr = Points to a block into which data is read size = Length of each item read, in bytessize = Length of each item read, in bytes n = Number of items readn = Number of items read stream = file pointerstream = file pointer
  • 20. ExampleExample Example:Example: #include <stdio.h>#include <stdio.h> int main()int main() {{ FILE *f;FILE *f; char buffer[11];char buffer[11]; if (f = fopen("fred.txt", “r”))if (f = fopen("fred.txt", “r”)) {{ fread(buffer, 1, 10, f);fread(buffer, 1, 10, f); buffer[10] = 0;buffer[10] = 0; fclose(f);fclose(f); printf("first 10 characters of the file:n%sn", buffer);printf("first 10 characters of the file:n%sn", buffer); }} return 0;return 0; }}
  • 21. fwrite()fwrite() Declaration:Declaration: size_t fwrite(const void *ptr, size_t size, size_t n, FILE*stream);size_t fwrite(const void *ptr, size_t size, size_t n, FILE*stream); Remarks:Remarks: fwrite appends a specified number of equal-sized data items to anfwrite appends a specified number of equal-sized data items to an output file.output file. ptr = Pointer to any object; the data written begins at ptrptr = Pointer to any object; the data written begins at ptr size = Length of each item of datasize = Length of each item of data n =Number of data items to be appendedn =Number of data items to be appended stream = file pointerstream = file pointer
  • 22. ExampleExample Example:Example: #include <stdio.h>#include <stdio.h> int main()int main() {{ char a[10]={'1','2','3','4','5','6','7','8','9','a'};char a[10]={'1','2','3','4','5','6','7','8','9','a'}; FILE *fs;FILE *fs; fs=fopen("Project.txt","w");fs=fopen("Project.txt","w"); fwrite(a,1,10,fs);fwrite(a,1,10,fs); fclose(fs);fclose(fs); return 0;return 0; }}
  • 23. fseek()fseek() This function sets the file position indicator for the stream pointed to by streamThis 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.or you can say it seeks a specified place within a file and modify it. SEEK_SETSEEK_SET Seeks from beginning of fileSeeks from beginning of file SEEK_CURSEEK_CUR Seeks from current positionSeeks from current position SEEK_ENDSEEK_END Seeks from end of fileSeeks from end of file Example:Example: #include#include <stdio.h><stdio.h> intint mainmain()() {{ FILE * f;FILE * f; f = fopen("myfile.txt", "w");f = fopen("myfile.txt", "w"); fputs("Hello World", f);fputs("Hello World", f); fseek(f, 6, SEEK_SET); SEEK_CUR, SEEK_ENDfseek(f, 6, SEEK_SET); SEEK_CUR, SEEK_END fputs(" India", f);fputs(" India", f); fclose(f);fclose(f); returnreturn 0;0; }}
  • 24. ftell()ftell() offset = ftell( file pointer );offset = ftell( file pointer ); "ftell" returns the current position for input or output on the file"ftell" returns the current position for input or output on the file #include <stdio.h>#include <stdio.h> int main(void)int main(void) {{ FILE *stream;FILE *stream; stream = fopen("MYFILE.TXT", "w");stream = fopen("MYFILE.TXT", "w"); fprintf(stream, "This is a test");fprintf(stream, "This is a test"); printf("The file pointer is at byte %ldn", ftell(stream));printf("The file pointer is at byte %ldn", ftell(stream)); fclose(stream);fclose(stream); return 0;return 0; }}
  • 25. Thank you This presentation is created using LibreOffice Impress 3.6.2.2