SlideShare uma empresa Scribd logo
1 de 20
FILE HANDLING IN C
File Handling in C:
File handling in C enables us to create, update, read,
and delete the files stored on the local file system
through our C program. The following operations can
be performed on a file.
1. Creation of the new file
2. Opening an existing file
3. Reading from the file
4. Writing to the file
5. Deleting the file
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()
We must open a file before it can be read, write, or update. The fopen() function is used to
open a file. The syntax of the fopen() is given below.
1. FILE *fopen( const char * filename, const char * mode );
The fopen() function accepts two parameters:
o The file name (string). If the file is stored at some specific location, then we must
mention the path at which the file is stored. For example, a file name can be
like "c://some_folder/some_file.ext".
o The mode in which the file is to be opened. It is a string.
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
Consider the following example which opens a file in write mode.
1. #include<stdio.h>
2. void main( )
3. {
4. FILE *fp ;
5. char ch ;
6. fp = fopen("file_handle.c","r") ;
7. while ( 1 )
8. {
9. ch = fgetc ( fp ) ;
10. if ( ch == EOF )
11. break ;
12. printf("%c",ch) ;
13. }
14. fclose (fp ) ;
15. }
Output
The content of the file will be printed.
#include;
void main( )
{
FILE *fp; // file pointer
char ch;
fp = fopen("file_handle.c","r");
while ( 1 )
{
ch = fgetc ( fp ); //Each character of the file is read and stored in the
character file.
if ( ch == EOF )
break;
printf("%c",ch);
}
fclose (fp );
}
Closing File: fclose()
 The fclose() function is used to close a file. The file
must be closed after performing all the operations on
it. The syntax of fclose() function is given below:
 int fclose( FILE *fp );
C fprintf() and fscanf()
Writing File : fprintf() function
The fprintf() function is used to write set of characters into file. It sends formatted output to
a stream.
Syntax:
1. int fprintf(FILE *stream, const char *format [, argument, ...])
Example:
1. #include <stdio.h>
2. main(){
3. FILE *fp;
4. fp = fopen("file.txt", "w");//opening file
5. fprintf(fp, "Hello file by fprintf...n");//writing data into file
6. fclose(fp);//closing file
7. }
Reading File : fscanf() function
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:
1. int fscanf(FILE *stream, const char *format [, argument, ...])
Example:
1. #include <stdio.h>
2. main(){
3. FILE *fp;
4. char buff[255];//creating char array to store data of file
5. fp = fopen("file.txt", "r");
6. while(fscanf(fp, "%s", buff)!=EOF){
7. printf("%s ", buff );
8. }
9. fclose(fp);
10. }
Output:
Hello file by fprintf...
C fputc() and fgetc()
Writing File : fputc() function
The fputc() function is used to write a single character into file. It outputs a character to a
stream.
Syntax:
1. int fputc(int c, FILE *stream)
Example:
1. #include <stdio.h>
2. main(){
3. FILE *fp;
4. fp = fopen("file1.txt", "w");//opening file
5. fputc('a',fp);//writing single character into file
6. fclose(fp);//closing file
7. }
file1.txt
a
Reading File : fgetc() function
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:
1. int fgetc(FILE *stream)
Example:
1. #include<stdio.h>
2. #include<conio.h>
3. void main(){
4. FILE *fp;
5. char c;
6. clrscr();
7. fp=fopen("myfile.txt","r");
8.
9. while((c=fgetc(fp))!=EOF){
10. printf("%c",c);
11. }
12. fclose(fp);
13. getch();
14. }
myfile.txt
this is simple text message
C 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:
1. int fseek(FILE *stream, long int offset, int whence)
There are 3 constants used in the fseek() function for whence: SEEK_SET, SEEK_CUR and
SEEK_END.
Example:
1. #include <stdio.h>
2. void main(){
3. FILE *fp;
4.
5. fp = fopen("myfile.txt","w+");
6. fputs("This is javatpoint", fp);
7.
8. fseek( fp, 7, SEEK_SET );
9. fputs("sonoo jaiswal", fp);
10. fclose(fp);
11. }
myfile.txt
This is sonoo jaiswal
Random Access To File:
There is no need to read each record sequentially, if
we want to access a particular record.C supports
these functions for random access file processing.
1. fseek()
2. ftell()
3. rewind()
fseek():
Thisfunction isused for seekingthepointer position in thefileat thespecified byte.
Syntax: fseek( filepointer,displacement, pointer position);
Where
file pointer ---- It isthepointer which pointsto thefile.
displacement ---- It ispositiveor negative.Thisisthenumber of byteswhich areskipped backward (if
negative) or forward( if positive) from thecurrent position.Thisisattached with Lbecausethisisalong
integer.
Pointer position:
Thissetsthepointer position in thefile.
Value pointer position
0 Beginning of file.
1 Current position
2 End of file
Example:
1) fseek( p,10L,0)
0 means pointer position is on beginning of the file,from this
statement pointer position is skipped 10 bytes from the
beginning of the file.
2)fseek( p,5L,1)
1 means current position of the pointer position.From this
statement pointer position is skipped 5 bytes forward from
the current position.
3)fseek(p,-5L,1)
From this statement pointer position is skipped 5 bytes
backward from the current position.
ftell():
 This function returns the value of the current pointer
position in the file.The value is count from the
beginning of the file.
Syntax: ftell(fptr);
Where fptr is a file pointer.
rewind():
 This function is used to move the file pointer to the
beginning of the given file.
Syntax: rewind( fptr);
Where fptr is a file pointer.
Binary files:
Binary files are very similar to arrays of structures, except
the structures are in a disk file rather than in an array in
memory. Because the structures in a binary file are on disk,
you can create very large collections of them (limited only
by your available disk space). They are also permanent
and always available. The only disadvantage is the
slowness that comes from disk access time.
Binary files have two features that distinguish them from
text files:
 You can jump instantly to any structure in the file, which
provides random access as in an array.
 You can change the contents of a structure anywhere in
the file at any time.
Binary files also usually have faster read and write times
than text files, because a binary image of the record is
stored directly from memory to disk (or vice versa). In a text
file, everything has to be converted back and forth to text,
and this takes time.
Command Line Arguments in C
 The arguments passed from command line are
called command line arguments. These arguments
are handled by main() function.
 To support command line argument, you need to
change the structure of main() function as given
below.
 int main(int argc, char *argv[] )
 Here, argc counts the number of arguments. It
counts the file name as the first argument.
 The argv[] contains the total number of arguments.
The first argument is the file name always.
Example
Let's see the example of command line arguments where we are passing one argument with
file name.
1. #include <stdio.h>
2. void main(int argc, char *argv[] ) {
3.
4. printf("Program name is: %sn", argv[0]);
5.
6. if(argc < 2){
7. printf("No argument passed through command line.n");
8. }
9. else{
10. printf("First argument is: %sn", argv[1]);
11. }
12. }
1. program.exe hello
Output:
Program name is: program
First argument is: hello
Run the program as follows in Windows from command line:
1. program.exe hello
Output:
Program name is: program
First argument is: hello
If you pass many arguments, it will print only one.
1. ./program hello c how r u
Output:
Program name is: program
First argument is: hello
But if you pass many arguments within double quote, all arguments will be treated as a
single argument only.
1. ./program "hello c how r u"
Output:
Program name is: program
First argument is: hello c how r u
You can write your program to print all the arguments. In this program, we are printing only
argv[1], that is why it is printing only one argument.

Mais conteúdo relacionado

Mais procurados

Mais procurados (20)

Structures in c language
Structures in c languageStructures in c language
Structures in c language
 
Strings
StringsStrings
Strings
 
File handling-c
File handling-cFile handling-c
File handling-c
 
Pointers in c++
Pointers in c++Pointers in c++
Pointers in c++
 
Function in C program
Function in C programFunction in C program
Function in C program
 
Dynamic memory allocation
Dynamic memory allocationDynamic memory allocation
Dynamic memory allocation
 
Functions in python
Functions in pythonFunctions in python
Functions in python
 
Strings in C
Strings in CStrings in C
Strings in C
 
C programming - Pointers
C programming - PointersC programming - Pointers
C programming - Pointers
 
Class and object in C++
Class and object in C++Class and object in C++
Class and object in C++
 
Python programming : Files
Python programming : FilesPython programming : Files
Python programming : Files
 
Files in C
Files in CFiles in C
Files in C
 
C programing -Structure
C programing -StructureC programing -Structure
C programing -Structure
 
Functions and modules in python
Functions and modules in pythonFunctions and modules in python
Functions and modules in python
 
File handling in c
File handling in cFile handling in c
File handling in c
 
File Handling Python
File Handling PythonFile Handling Python
File Handling Python
 
Pointer in c
Pointer in cPointer in c
Pointer in c
 
Nested structure (Computer programming and utilization)
Nested structure (Computer programming and utilization)Nested structure (Computer programming and utilization)
Nested structure (Computer programming and utilization)
 
Python Modules
Python ModulesPython Modules
Python Modules
 
Modules and packages in python
Modules and packages in pythonModules and packages in python
Modules and packages in python
 

Semelhante a C Programming Unit-5 (20)

ppt5-190810161800 (1).pdf
ppt5-190810161800 (1).pdfppt5-190810161800 (1).pdf
ppt5-190810161800 (1).pdf
 
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
 
Module 5 file cp
Module 5 file cpModule 5 file cp
Module 5 file cp
 
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
 
Unit5
Unit5Unit5
Unit5
 
Unit 5 dwqb ans
Unit 5 dwqb ansUnit 5 dwqb ans
Unit 5 dwqb ans
 
Handout#01
Handout#01Handout#01
Handout#01
 
File management
File managementFile management
File management
 
File Handling in C Programming
File Handling in C ProgrammingFile Handling in C Programming
File Handling in C Programming
 
Unit 8
Unit 8Unit 8
Unit 8
 
Chapter 13.1.10
Chapter 13.1.10Chapter 13.1.10
Chapter 13.1.10
 
file handling1
file handling1file handling1
file handling1
 
FILES IN C
FILES IN CFILES IN C
FILES IN C
 
File Handling in C
File Handling in CFile Handling in C
File Handling in C
 
PPS-II UNIT-5 PPT.pptx
PPS-II  UNIT-5 PPT.pptxPPS-II  UNIT-5 PPT.pptx
PPS-II UNIT-5 PPT.pptx
 
File Organization
File OrganizationFile Organization
File Organization
 
C programming session 08
C programming session 08C programming session 08
C programming session 08
 
Chap 12(files)
Chap 12(files)Chap 12(files)
Chap 12(files)
 
File Handling in C.pptx
File Handling in C.pptxFile Handling in C.pptx
File Handling in C.pptx
 
File Management in C
File Management in CFile Management in C
File Management in C
 

Mais de Vikram Nandini

IoT: From Copper strip to Gold Bar
IoT: From Copper strip to Gold BarIoT: From Copper strip to Gold Bar
IoT: From Copper strip to Gold BarVikram Nandini
 
Linux File Trees and Commands
Linux File Trees and CommandsLinux File Trees and Commands
Linux File Trees and CommandsVikram Nandini
 
Introduction to Linux & Basic Commands
Introduction to Linux & Basic CommandsIntroduction to Linux & Basic Commands
Introduction to Linux & Basic CommandsVikram Nandini
 
Manufacturing - II Part
Manufacturing - II PartManufacturing - II Part
Manufacturing - II PartVikram Nandini
 
Prototyping Online Components
Prototyping Online ComponentsPrototyping Online Components
Prototyping Online ComponentsVikram Nandini
 
Artificial Neural Networks
Artificial Neural NetworksArtificial Neural Networks
Artificial Neural NetworksVikram Nandini
 
Design Principles for Connected Devices
Design Principles for Connected DevicesDesign Principles for Connected Devices
Design Principles for Connected DevicesVikram Nandini
 
Communication in the IoT
Communication in the IoTCommunication in the IoT
Communication in the IoTVikram Nandini
 
Introduction to Cyber Security
Introduction to Cyber SecurityIntroduction to Cyber Security
Introduction to Cyber SecurityVikram Nandini
 
cloud computing UNIT-2.pdf
cloud computing UNIT-2.pdfcloud computing UNIT-2.pdf
cloud computing UNIT-2.pdfVikram Nandini
 
Introduction to Web Technologies
Introduction to Web TechnologiesIntroduction to Web Technologies
Introduction to Web TechnologiesVikram Nandini
 
Cascading Style Sheets
Cascading Style SheetsCascading Style Sheets
Cascading Style SheetsVikram Nandini
 

Mais de Vikram Nandini (20)

IoT: From Copper strip to Gold Bar
IoT: From Copper strip to Gold BarIoT: From Copper strip to Gold Bar
IoT: From Copper strip to Gold Bar
 
Design Patterns
Design PatternsDesign Patterns
Design Patterns
 
Linux File Trees and Commands
Linux File Trees and CommandsLinux File Trees and Commands
Linux File Trees and Commands
 
Introduction to Linux & Basic Commands
Introduction to Linux & Basic CommandsIntroduction to Linux & Basic Commands
Introduction to Linux & Basic Commands
 
INTRODUCTION to OOAD
INTRODUCTION to OOADINTRODUCTION to OOAD
INTRODUCTION to OOAD
 
Ethics
EthicsEthics
Ethics
 
Manufacturing - II Part
Manufacturing - II PartManufacturing - II Part
Manufacturing - II Part
 
Manufacturing
ManufacturingManufacturing
Manufacturing
 
Business Models
Business ModelsBusiness Models
Business Models
 
Prototyping Online Components
Prototyping Online ComponentsPrototyping Online Components
Prototyping Online Components
 
Artificial Neural Networks
Artificial Neural NetworksArtificial Neural Networks
Artificial Neural Networks
 
IoT-Prototyping
IoT-PrototypingIoT-Prototyping
IoT-Prototyping
 
Design Principles for Connected Devices
Design Principles for Connected DevicesDesign Principles for Connected Devices
Design Principles for Connected Devices
 
Introduction to IoT
Introduction to IoTIntroduction to IoT
Introduction to IoT
 
Embedded decices
Embedded decicesEmbedded decices
Embedded decices
 
Communication in the IoT
Communication in the IoTCommunication in the IoT
Communication in the IoT
 
Introduction to Cyber Security
Introduction to Cyber SecurityIntroduction to Cyber Security
Introduction to Cyber Security
 
cloud computing UNIT-2.pdf
cloud computing UNIT-2.pdfcloud computing UNIT-2.pdf
cloud computing UNIT-2.pdf
 
Introduction to Web Technologies
Introduction to Web TechnologiesIntroduction to Web Technologies
Introduction to Web Technologies
 
Cascading Style Sheets
Cascading Style SheetsCascading Style Sheets
Cascading Style Sheets
 

Último

Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpinRaunakKeshri1
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdfQucHHunhnh
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfagholdier
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Celine George
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsTechSoup
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformChameera Dedduwage
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactPECB
 
9548086042 for call girls in Indira Nagar with room service
9548086042  for call girls in Indira Nagar  with room service9548086042  for call girls in Indira Nagar  with room service
9548086042 for call girls in Indira Nagar with room servicediscovermytutordmt
 
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...Sapna Thakur
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Disha Kariya
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfAyushMahapatra5
 
fourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingfourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingTeacherCyreneCayanan
 
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...fonyou31
 
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
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxVishalSingh1417
 

Último (20)

Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpin
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
9548086042 for call girls in Indira Nagar with room service
9548086042  for call girls in Indira Nagar  with room service9548086042  for call girls in Indira Nagar  with room service
9548086042 for call girls in Indira Nagar with room service
 
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdf
 
fourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingfourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writing
 
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
 
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
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 

C Programming Unit-5

  • 2. File Handling in C: File handling in C enables us to create, update, read, and delete the files stored on the local file system through our C program. The following operations can be performed on a file. 1. Creation of the new file 2. Opening an existing file 3. Reading from the file 4. Writing to the file 5. Deleting the file
  • 3. 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
  • 4. Opening File: fopen() We must open a file before it can be read, write, or update. The fopen() function is used to open a file. The syntax of the fopen() is given below. 1. FILE *fopen( const char * filename, const char * mode ); The fopen() function accepts two parameters: o The file name (string). If the file is stored at some specific location, then we must mention the path at which the file is stored. For example, a file name can be like "c://some_folder/some_file.ext". o The mode in which the file is to be opened. It is a string.
  • 5. 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
  • 6. Consider the following example which opens a file in write mode. 1. #include<stdio.h> 2. void main( ) 3. { 4. FILE *fp ; 5. char ch ; 6. fp = fopen("file_handle.c","r") ; 7. while ( 1 ) 8. { 9. ch = fgetc ( fp ) ; 10. if ( ch == EOF ) 11. break ; 12. printf("%c",ch) ; 13. } 14. fclose (fp ) ; 15. } Output The content of the file will be printed. #include; void main( ) { FILE *fp; // file pointer char ch; fp = fopen("file_handle.c","r"); while ( 1 ) { ch = fgetc ( fp ); //Each character of the file is read and stored in the character file. if ( ch == EOF ) break; printf("%c",ch); } fclose (fp ); }
  • 7. Closing File: fclose()  The fclose() function is used to close a file. The file must be closed after performing all the operations on it. The syntax of fclose() function is given below:  int fclose( FILE *fp );
  • 8. C fprintf() and fscanf() Writing File : fprintf() function The fprintf() function is used to write set of characters into file. It sends formatted output to a stream. Syntax: 1. int fprintf(FILE *stream, const char *format [, argument, ...]) Example: 1. #include <stdio.h> 2. main(){ 3. FILE *fp; 4. fp = fopen("file.txt", "w");//opening file 5. fprintf(fp, "Hello file by fprintf...n");//writing data into file 6. fclose(fp);//closing file 7. }
  • 9. Reading File : fscanf() function 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: 1. int fscanf(FILE *stream, const char *format [, argument, ...]) Example: 1. #include <stdio.h> 2. main(){ 3. FILE *fp; 4. char buff[255];//creating char array to store data of file 5. fp = fopen("file.txt", "r"); 6. while(fscanf(fp, "%s", buff)!=EOF){ 7. printf("%s ", buff ); 8. } 9. fclose(fp); 10. } Output: Hello file by fprintf...
  • 10. C fputc() and fgetc() Writing File : fputc() function The fputc() function is used to write a single character into file. It outputs a character to a stream. Syntax: 1. int fputc(int c, FILE *stream) Example: 1. #include <stdio.h> 2. main(){ 3. FILE *fp; 4. fp = fopen("file1.txt", "w");//opening file 5. fputc('a',fp);//writing single character into file 6. fclose(fp);//closing file 7. } file1.txt a
  • 11. Reading File : fgetc() function 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: 1. int fgetc(FILE *stream) Example: 1. #include<stdio.h> 2. #include<conio.h> 3. void main(){ 4. FILE *fp; 5. char c; 6. clrscr(); 7. fp=fopen("myfile.txt","r"); 8. 9. while((c=fgetc(fp))!=EOF){ 10. printf("%c",c); 11. } 12. fclose(fp); 13. getch(); 14. } myfile.txt this is simple text message
  • 12. C 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: 1. int fseek(FILE *stream, long int offset, int whence) There are 3 constants used in the fseek() function for whence: SEEK_SET, SEEK_CUR and SEEK_END. Example: 1. #include <stdio.h> 2. void main(){ 3. FILE *fp; 4. 5. fp = fopen("myfile.txt","w+"); 6. fputs("This is javatpoint", fp); 7. 8. fseek( fp, 7, SEEK_SET ); 9. fputs("sonoo jaiswal", fp); 10. fclose(fp); 11. } myfile.txt This is sonoo jaiswal
  • 13. Random Access To File: There is no need to read each record sequentially, if we want to access a particular record.C supports these functions for random access file processing. 1. fseek() 2. ftell() 3. rewind()
  • 14. fseek(): Thisfunction isused for seekingthepointer position in thefileat thespecified byte. Syntax: fseek( filepointer,displacement, pointer position); Where file pointer ---- It isthepointer which pointsto thefile. displacement ---- It ispositiveor negative.Thisisthenumber of byteswhich areskipped backward (if negative) or forward( if positive) from thecurrent position.Thisisattached with Lbecausethisisalong integer. Pointer position: Thissetsthepointer position in thefile. Value pointer position 0 Beginning of file. 1 Current position 2 End of file
  • 15. Example: 1) fseek( p,10L,0) 0 means pointer position is on beginning of the file,from this statement pointer position is skipped 10 bytes from the beginning of the file. 2)fseek( p,5L,1) 1 means current position of the pointer position.From this statement pointer position is skipped 5 bytes forward from the current position. 3)fseek(p,-5L,1) From this statement pointer position is skipped 5 bytes backward from the current position.
  • 16. ftell():  This function returns the value of the current pointer position in the file.The value is count from the beginning of the file. Syntax: ftell(fptr); Where fptr is a file pointer. rewind():  This function is used to move the file pointer to the beginning of the given file. Syntax: rewind( fptr); Where fptr is a file pointer.
  • 17. Binary files: Binary files are very similar to arrays of structures, except the structures are in a disk file rather than in an array in memory. Because the structures in a binary file are on disk, you can create very large collections of them (limited only by your available disk space). They are also permanent and always available. The only disadvantage is the slowness that comes from disk access time. Binary files have two features that distinguish them from text files:  You can jump instantly to any structure in the file, which provides random access as in an array.  You can change the contents of a structure anywhere in the file at any time. Binary files also usually have faster read and write times than text files, because a binary image of the record is stored directly from memory to disk (or vice versa). In a text file, everything has to be converted back and forth to text, and this takes time.
  • 18. Command Line Arguments in C  The arguments passed from command line are called command line arguments. These arguments are handled by main() function.  To support command line argument, you need to change the structure of main() function as given below.  int main(int argc, char *argv[] )  Here, argc counts the number of arguments. It counts the file name as the first argument.  The argv[] contains the total number of arguments. The first argument is the file name always.
  • 19. Example Let's see the example of command line arguments where we are passing one argument with file name. 1. #include <stdio.h> 2. void main(int argc, char *argv[] ) { 3. 4. printf("Program name is: %sn", argv[0]); 5. 6. if(argc < 2){ 7. printf("No argument passed through command line.n"); 8. } 9. else{ 10. printf("First argument is: %sn", argv[1]); 11. } 12. } 1. program.exe hello Output: Program name is: program First argument is: hello
  • 20. Run the program as follows in Windows from command line: 1. program.exe hello Output: Program name is: program First argument is: hello If you pass many arguments, it will print only one. 1. ./program hello c how r u Output: Program name is: program First argument is: hello But if you pass many arguments within double quote, all arguments will be treated as a single argument only. 1. ./program "hello c how r u" Output: Program name is: program First argument is: hello c how r u You can write your program to print all the arguments. In this program, we are printing only argv[1], that is why it is printing only one argument.