SlideShare a Scribd company logo
1 of 23
File Handling
Md. Imran Hossain Showrov (showrovsworld@gmail.com)
20
1
Outline
 What is a File?
 Steps in Processing a File
 The Basic File Operations
 File Open Modes
 File Open
 Closing a File
 Reading and Writing Files
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
 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
File Open Modes: In Addition
 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
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
#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
#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;
}
Lecture 20 - File Handling

More Related Content

What's hot (20)

File in C Programming
File in C ProgrammingFile in C Programming
File in C Programming
 
File handling in 'C'
File handling in 'C'File handling in 'C'
File handling in 'C'
 
File handling in c
File handling in c File handling in c
File handling in c
 
Module 03 File Handling in C
Module 03 File Handling in CModule 03 File Handling in C
Module 03 File Handling in C
 
File handling in C by Faixan
File handling in C by FaixanFile handling in C by Faixan
File handling in C by Faixan
 
1file handling
1file handling1file handling
1file handling
 
File handling in C
File handling in CFile handling in C
File handling in C
 
file
filefile
file
 
file management in c language
file management in c languagefile management in c language
file management in c language
 
File handling-c
File handling-cFile handling-c
File handling-c
 
File Management in C
File Management in CFile Management in C
File Management in C
 
File handling in c
File handling in cFile handling in c
File handling in c
 
File in C programming
File in C programmingFile in C programming
File in C programming
 
File handling
File handlingFile handling
File handling
 
File_Management_in_C
File_Management_in_CFile_Management_in_C
File_Management_in_C
 
Files in C
Files in CFiles in C
Files in C
 
File management and handling by prabhakar
File management and handling by prabhakarFile management and handling by prabhakar
File management and handling by prabhakar
 
File handling-c programming language
File handling-c programming languageFile handling-c programming language
File handling-c programming language
 
File handling in c
File  handling in cFile  handling in c
File handling in c
 
PHP - Introduction to File Handling with PHP
PHP -  Introduction to  File Handling with PHPPHP -  Introduction to  File Handling with PHP
PHP - Introduction to File Handling with PHP
 

Similar to Lecture 20 - File Handling

EASY UNDERSTANDING OF FILES IN C LANGUAGE.pdf
EASY UNDERSTANDING OF FILES IN C LANGUAGE.pdfEASY UNDERSTANDING OF FILES IN C LANGUAGE.pdf
EASY UNDERSTANDING OF FILES IN C LANGUAGE.pdfsudhakargeruganti
 
file_handling_in_c.ppt
file_handling_in_c.pptfile_handling_in_c.ppt
file_handling_in_c.pptyuvrajkeshri
 
INput output stream in ccP Full Detail.pptx
INput output stream in ccP Full Detail.pptxINput output stream in ccP Full Detail.pptx
INput output stream in ccP Full Detail.pptxAssadLeo1
 
File handling in c
File handling in cFile handling in c
File handling in caakanksha s
 
File handling-dutt
File handling-duttFile handling-dutt
File handling-duttAnil Dutt
 
Data Structure Using C - FILES
Data Structure Using C - FILESData Structure Using C - FILES
Data Structure Using C - FILESHarish Kamat
 
C UNIT-5 PREPARED BY M V BRAHMANANDA REDDY
C UNIT-5 PREPARED BY M V BRAHMANANDA REDDYC UNIT-5 PREPARED BY M V BRAHMANANDA REDDY
C UNIT-5 PREPARED BY M V BRAHMANANDA REDDYRajeshkumar Reddy
 
Mesics lecture files in 'c'
Mesics lecture   files in 'c'Mesics lecture   files in 'c'
Mesics lecture files in 'c'eShikshak
 
Advance C Programming UNIT 4-FILE HANDLING IN C.pdf
Advance C Programming UNIT 4-FILE HANDLING IN C.pdfAdvance C Programming UNIT 4-FILE HANDLING IN C.pdf
Advance C Programming UNIT 4-FILE HANDLING IN C.pdfsangeeta borde
 
C-FILE MANAGEMENT.pptx
C-FILE MANAGEMENT.pptxC-FILE MANAGEMENT.pptx
C-FILE MANAGEMENT.pptxbanu236831
 

Similar to Lecture 20 - File Handling (20)

File in C language
File in C languageFile in C language
File in C language
 
Unit 8
Unit 8Unit 8
Unit 8
 
File management
File managementFile management
File management
 
PPS PPT 2.pptx
PPS PPT 2.pptxPPS PPT 2.pptx
PPS PPT 2.pptx
 
Unit-VI.pptx
Unit-VI.pptxUnit-VI.pptx
Unit-VI.pptx
 
EASY UNDERSTANDING OF FILES IN C LANGUAGE.pdf
EASY UNDERSTANDING OF FILES IN C LANGUAGE.pdfEASY UNDERSTANDING OF FILES IN C LANGUAGE.pdf
EASY UNDERSTANDING OF FILES IN C LANGUAGE.pdf
 
file_handling_in_c.ppt
file_handling_in_c.pptfile_handling_in_c.ppt
file_handling_in_c.ppt
 
Unit5
Unit5Unit5
Unit5
 
FILES IN C
FILES IN CFILES IN C
FILES IN C
 
Files_in_C.ppt
Files_in_C.pptFiles_in_C.ppt
Files_in_C.ppt
 
INput output stream in ccP Full Detail.pptx
INput output stream in ccP Full Detail.pptxINput output stream in ccP Full Detail.pptx
INput output stream in ccP Full Detail.pptx
 
File handling in c
File handling in cFile handling in c
File handling in c
 
file_handling_in_c.ppt
file_handling_in_c.pptfile_handling_in_c.ppt
file_handling_in_c.ppt
 
File handling-dutt
File handling-duttFile handling-dutt
File handling-dutt
 
Data Structure Using C - FILES
Data Structure Using C - FILESData Structure Using C - FILES
Data Structure Using C - FILES
 
C UNIT-5 PREPARED BY M V BRAHMANANDA REDDY
C UNIT-5 PREPARED BY M V BRAHMANANDA REDDYC UNIT-5 PREPARED BY M V BRAHMANANDA REDDY
C UNIT-5 PREPARED BY M V BRAHMANANDA REDDY
 
File handling C program
File handling C programFile handling C program
File handling C program
 
Mesics lecture files in 'c'
Mesics lecture   files in 'c'Mesics lecture   files in 'c'
Mesics lecture files in 'c'
 
Advance C Programming UNIT 4-FILE HANDLING IN C.pdf
Advance C Programming UNIT 4-FILE HANDLING IN C.pdfAdvance C Programming UNIT 4-FILE HANDLING IN C.pdf
Advance C Programming UNIT 4-FILE HANDLING IN C.pdf
 
C-FILE MANAGEMENT.pptx
C-FILE MANAGEMENT.pptxC-FILE MANAGEMENT.pptx
C-FILE MANAGEMENT.pptx
 

More from Md. Imran Hossain Showrov

Lecture 5 - Structured Programming Language
Lecture 5 - Structured Programming Language Lecture 5 - Structured Programming Language
Lecture 5 - Structured Programming Language Md. Imran Hossain Showrov
 
Lecture 3 - Processors, Memory and I/O devices
Lecture 3 - Processors, Memory and I/O devicesLecture 3 - Processors, Memory and I/O devices
Lecture 3 - Processors, Memory and I/O devicesMd. Imran Hossain Showrov
 

More from Md. Imran Hossain Showrov (20)

Lecture 22 - Error Handling
Lecture 22 - Error HandlingLecture 22 - Error Handling
Lecture 22 - Error Handling
 
Lecture 21 - Preprocessor and Header File
Lecture 21 - Preprocessor and Header FileLecture 21 - Preprocessor and Header File
Lecture 21 - Preprocessor and Header File
 
Lecture 19 - Struct and Union
Lecture 19 - Struct and UnionLecture 19 - Struct and Union
Lecture 19 - Struct and Union
 
Lecture 18 - Pointers
Lecture 18 - PointersLecture 18 - Pointers
Lecture 18 - Pointers
 
Lecture 16 - Multi dimensional Array
Lecture 16 - Multi dimensional ArrayLecture 16 - Multi dimensional Array
Lecture 16 - Multi dimensional Array
 
Lecture 17 - Strings
Lecture 17 - StringsLecture 17 - Strings
Lecture 17 - Strings
 
Lecture 15 - Array
Lecture 15 - ArrayLecture 15 - Array
Lecture 15 - Array
 
Lecture 14 - Scope Rules
Lecture 14 - Scope RulesLecture 14 - Scope Rules
Lecture 14 - Scope Rules
 
Lecture 13 - Storage Classes
Lecture 13 - Storage ClassesLecture 13 - Storage Classes
Lecture 13 - Storage Classes
 
Lecture 12 - Recursion
Lecture 12 - Recursion Lecture 12 - Recursion
Lecture 12 - Recursion
 
Lecture 11 - Functions
Lecture 11 - FunctionsLecture 11 - Functions
Lecture 11 - Functions
 
Lecture 10 - Control Structures 2
Lecture 10 - Control Structures 2Lecture 10 - Control Structures 2
Lecture 10 - Control Structures 2
 
Lecture 8- Data Input and Output
Lecture 8- Data Input and OutputLecture 8- Data Input and Output
Lecture 8- Data Input and Output
 
Lecture 9- Control Structures 1
Lecture 9- Control Structures 1Lecture 9- Control Structures 1
Lecture 9- Control Structures 1
 
Lecture 7- Operators and Expressions
Lecture 7- Operators and Expressions Lecture 7- Operators and Expressions
Lecture 7- Operators and Expressions
 
Lecture 6- Intorduction to C Programming
Lecture 6- Intorduction to C ProgrammingLecture 6- Intorduction to C Programming
Lecture 6- Intorduction to C Programming
 
Lecture 5 - Structured Programming Language
Lecture 5 - Structured Programming Language Lecture 5 - Structured Programming Language
Lecture 5 - Structured Programming Language
 
Lecture 4- Computer Software and Languages
Lecture 4- Computer Software and LanguagesLecture 4- Computer Software and Languages
Lecture 4- Computer Software and Languages
 
Lecture 3 - Processors, Memory and I/O devices
Lecture 3 - Processors, Memory and I/O devicesLecture 3 - Processors, Memory and I/O devices
Lecture 3 - Processors, Memory and I/O devices
 
Lecture 2 - Introductory Concepts
Lecture 2 - Introductory ConceptsLecture 2 - Introductory Concepts
Lecture 2 - Introductory Concepts
 

Recently uploaded

MENTAL STATUS EXAMINATION format.docx
MENTAL     STATUS EXAMINATION format.docxMENTAL     STATUS EXAMINATION format.docx
MENTAL STATUS EXAMINATION format.docxPoojaSen20
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsanshu789521
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxOH TEIK BIN
 
Science 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsScience 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsKarinaGenton
 
Concept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfConcept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfUmakantAnnand
 
Micromeritics - Fundamental and Derived Properties of Powders
Micromeritics - Fundamental and Derived Properties of PowdersMicromeritics - Fundamental and Derived Properties of Powders
Micromeritics - Fundamental and Derived Properties of PowdersChitralekhaTherkar
 
PSYCHIATRIC History collection FORMAT.pptx
PSYCHIATRIC   History collection FORMAT.pptxPSYCHIATRIC   History collection FORMAT.pptx
PSYCHIATRIC History collection FORMAT.pptxPoojaSen20
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdfssuser54595a
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionSafetyChain Software
 

Recently uploaded (20)

MENTAL STATUS EXAMINATION format.docx
MENTAL     STATUS EXAMINATION format.docxMENTAL     STATUS EXAMINATION format.docx
MENTAL STATUS EXAMINATION format.docx
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha elections
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 
Science 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsScience 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its Characteristics
 
Concept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfConcept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.Compdf
 
Micromeritics - Fundamental and Derived Properties of Powders
Micromeritics - Fundamental and Derived Properties of PowdersMicromeritics - Fundamental and Derived Properties of Powders
Micromeritics - Fundamental and Derived Properties of Powders
 
PSYCHIATRIC History collection FORMAT.pptx
PSYCHIATRIC   History collection FORMAT.pptxPSYCHIATRIC   History collection FORMAT.pptx
PSYCHIATRIC History collection FORMAT.pptx
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory Inspection
 

Lecture 20 - File Handling

  • 1. File Handling Md. Imran Hossain Showrov (showrovsworld@gmail.com) 20 1
  • 2. Outline  What is a File?  Steps in Processing a File  The Basic File Operations  File Open Modes  File Open  Closing a File  Reading and Writing Files
  • 3. 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.
  • 4. 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.
  • 5. The Basic File Operations  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.
  • 7. File Open Modes: In Addition  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”);
  • 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);
  • 13. fscanf() Syntax: fscanf (fp,"string",identifiers); Example: – FILE *fp; – Fp=fopen(“input.txt”,”r”); – int i; – fscanf (fp,“%d",i);
  • 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 #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 #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; }