Unit V
Files
Dr Namita Parati
Why File Handling in C?
• Permanent Storage: File handling allows the program to
store data persistently.
• Data Sharing: File handling enables data to be shared
between different programs.
• Large Data: File handling is ideal for dealing with large
amounts of data.
• Data Backup: File handling provides a way to create backups
of important data. Dr Namita Parati
STREAMS IN C
• In C, the standard streams are termed as pre-connected input and output
channels between a text terminal and the program (when it begins
execution).Therefore, stream is a logical interface to the devices that are
connected to the computer.
• Stream is widely used as a logical interface to a file where a file can refer to
a disk file, the computer screen, keyboard, etc. Although files may differ in
the form and capabilities, all streams are the same.
• The three standard streams in C languages are-
• standard input (stdin), standard output (stdout) and standard
error (stderr).
Dr Namita Parati
Dr Namita Parati
STREAMS IN C contd.
• Standard input (stdin): Standard input is the stream from which the program
receives its data. The program requests transfer of data using the read
operation. However, not all programs require input. Generally, unless
redirected, input for a program is expected from the keyboard.
• Standard output (stdout): Standard output is the stream where a program
writes its output data. The program requests data transfer using the write
operation. However, not all programs generate output.
• Standard error (stderr): Standard error is basically an output stream used by
programs to report error messages or diagnostics. It is a stream independent of
standard output and can be redirected separately. No doubt, the standard
output and standard error can also be directed to the same destination.
• A stream is linked to a file using an open operation and disassociated
from a file using a close operation.
KEYBOARD
PROGRAM
SCREEN
stdin
stderr
stdout
Dr Namita Parati
BUFFER ASSOCIATED WITH FILE STREAM
• When a stream linked to a disk file is created, a buffer is automatically created and associated with the stream. A buffer is
nothing but a block of memory that is used for temporary storage of data that has to be read from or written to a file.
• Buffers are needed because disk drives are block oriented devices as they can operate efficiently when data has to be
read/ written in blocks of certain size. The size of ideal buffer size is hardware dependant.
• The buffer acts as an interface between the stream (which is character-oriented) and the disk hardware (which is block
oriented). When the program has to write data to the stream, it is saved in the buffer till it is full. Then the entire contents
of the buffer are written to the disk as a block.
PROGRAM
BUFFER DISK
Program writes data to buffer
Data from the buffer is written to the disk file
Similarly, when reading data from a disk file, the data is read as a block from the file and written into
the buffer. The program reads data from the buffer. The creation and operation of the buffer is
automatically handled by the operating system. However, C provides some functions for buffer
manipulation. The data resides in the buffer until the buffer is flushed or written to a file.
Dr Namita Parati
Difference between Text File and Binary File
Text File Binary File
It contains alphabets and numbers which
are easily understood by human beings.
It contains 1’s and 0’s, which are easily
understood by computers.
An error in a text file can be eliminated
when seen.
The error in a binary file corrupts the file
and is not easy to detect.
Can store only plain text in a file.
Can store different types of data (image,
audio, text) in a single file.
Widely used file format and can be
opened using any simple text editor.
Developed especially for an application
and may not be understood by other
applications.
Mostly .txt is used as extensions to text
files.
Can have any application defined
extension.
Dr Namita Parati
Files can be accessed in 2 ways
• Sequential Access
It is the simplest access method. Information in the file is processed
in order, one after the other.
• Direct Access (Random Access)
Another method is direct access method also known as relative access
method.
A filed-length logical record that allows the program to read and
write record randomly in no particular order.
Dr Namita Parati
Sequential Versus Random Access
Dr Namita Parati
Dr Namita Parati
File handling operations
• File handling in C allows 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.
• Creation of the new file
• Opening an existing file
• Reading from the file
• Writing to the file
• Deleting the file
Dr Namita Parati
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 fputs() writes a string to file
7 fgets() reads a string from file
8 fclose() closes the file
9 fseek() sets the file pointer to given position
10 ftell() returns current position
11 rewind() sets the file pointer to the beginning of the file
Dr Namita Parati
Sequential Access Functions
Dr Namita Parati
Random Access Functions
Dr Namita Parati
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.
• FILE *fopen( const char * filename, const char * mode );
Dr Namita Parati
• The fopen() function accepts two parameters:
• 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".
• The mode in which the file is to be opened. It is a string.
Dr Namita Parati
We can use one of the following modes in the fopen() function.
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
Dr Namita Parati
The fopen function works in the following way.
• Firstly, It searches the file to be opened.
• Then, it loads the file from the disk and place it into the buffer. The
buffer is used to provide efficiency for the read operations.
• It sets up a character pointer which points to the first character of the
file.
Dr Namita Parati
fopen() example
// C program to illustrate fopen()
#include <stdio.h>
#include <stdlib.h>
main()
{
// pointer demo to FILE
FILE* fp;
// Creates a file "demo_file"
// with file acccess as write-plus mode
fp = fopen("demo_file.txt", "w+");
// adds content to the file
fprintf(demo, "%s %s %s", "Welcome", "to", “MVSR");
// closes the file pointed by fp
fclose(fp);
}
a new file will be created by the
name “demo_file” and with the
following content:
Welcome to MVSR
Dr Namita Parati
Example2 Reading Char by Char from a file
#include<stdio.h>
void main( )
{
FILE *fp ;
char ch ;
fp = fopen(“hello.c","r") ; //use existing file name
while ( 1 )
{
ch = fgetc ( fp ) ;
if ( ch == EOF )
break ;
printf("%c",ch) ;
}
fclose (fp ) ;
}
Dr Namita Parati
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 );
Dr Namita Parati
fprintf() function
• The fprintf() function is used to write set of characters into
file. It sends formatted output to a stream.
#include <stdio.h>
main(){
FILE *fp;
fp = fopen("file.txt", "w");//opening file
fprintf(fp, "Hello file by fprintf...n");//writing data into file
fclose(fp);//closing file
}
Dr Namita Parati
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.
#include <stdio.h>
main(){
FILE *fp;
char buff[255];//creating char array to store data of file
fp = fopen("file.txt", "r");
while(fscanf(fp, "%s", buff)!=EOF){
printf("%s ", buff );
}
fclose(fp);
}
Output:
Hello file by fprintf...
Dr Namita Parati
C File Example: Storing employee information
• file handling example to store employee information as entered by user from console.
• We are going to store id, name and salary of the employee.
#include <stdio.h>
void main()
{
FILE *fptr;
int id;
char name[30];
float salary;
fptr = fopen("emp.txt", "w+");/* open for writing */
if (fptr == NULL)
{
printf("File does not exists n");
return;
}
Dr Namita Parati
printf("Enter the idn");
scanf("%d", &id);
fprintf(fptr, "Id= %dn", id);
printf("Enter the name n");
scanf("%s", name);
fprintf(fptr, "Name= %sn", name);
printf("Enter the salaryn");
scanf("%f", &salary);
fprintf(fptr, "Salary= %.2fn", salary);
fclose(fptr);
}
Output:
Enter the id 1
Enter the name Ravi
Enter the salary
120000
Dr Namita Parati
Now open file from current directory.
you will see emp.txt file. It will have following
information.
emp.txt
Id= 1 Name= Ravi Salary= 120000
Dr Namita Parati
fputc() function
• The fputc() function is used to write a single character into file.
• It outputs a character to a stream.
#include <stdio.h>
main(){
FILE *fp;
fp = fopen("file1.txt", "w");//opening file
fputc('a',fp);//writing single character into file
fclose(fp);//closing file
}
file1.txt
a
Dr Namita Parati
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.
#include<stdio.h>
void main(){
FILE *fp;
char c;
fp=fopen("myfile.txt","r");
while((c=fgetc(fp))!=EOF)
{
printf("%c",c);
}
fclose(fp);
}
Dr Namita Parati
fputs() function
• The fputs() function writes a line of characters into file. It outputs
string to a stream.
#include<stdio.h>
void main(){
FILE *fp;
fp=fopen("myfile2.txt","w");
fputs("hello c programming",fp);
fclose(fp);
}
Dr Namita Parati
fgets() function
• The fgets() function reads a line of characters from file. It gets string
from a stream.
#include<stdio.h>
void main(){
FILE *fp;
char text[300];
fp=fopen("myfile2.txt","r");
printf("%s",fgets(text,200,fp));
fclose(fp);
}
Dr Namita Parati
fseek() function
• The fseek() function is used to set the file pointer to the specified
offset(address). It is used to write data into file at desired location.
#include <stdio.h>
void main(){
FILE *fp;
fp = fopen("myfile.txt","w+");
fputs("This is last unit", fp);
fseek( fp, 7, SEEK_SET );
fputs(“important", fp);
fclose(fp);
}
myfile.txt
This is important
Dr Namita Parati
rewind() function
• The rewind() function sets the file pointer at the beginning of the
stream. It is useful if you have to use stream many times.
#include<stdio.h>
void main(){
FILE *fp;
char c;
fp=fopen("file.txt","r");
Dr Namita Parati
while((c=fgetc(fp))!=EOF){
printf("%c",c);
}
rewind(fp);//moves the file pointer at beginning of the file
while((c=fgetc(fp))!=EOF){
printf("%c",c);
}
fclose(fp);
}
Output:
this is a simple textthis is a simple
text
Dr Namita Parati
ftell() function
• The ftell() function returns the current file position of the specified stream.
We can use ftell() function to get the total size of a file after moving file
pointer at the end of file.
#include <stdio.h>
void main (){
FILE *fp;
int length;
clrscr();
fp = fopen("file.txt", "r");
fseek(fp, 0, SEEK_END);
length = ftell(fp);
fclose(fp);
printf("Size of file: %d bytes", length);
}
Output:
Size of file: 21 bytes
Dr Namita Parati
C program to copy the contents of one file to another file
#include <iostream>
#include <stdlib.h>
int main() {
char ch;// source_file[20], target_file[20];
FILE *source, *target;
char source_file[]="x1.txt";
char target_file[]="x2.txt";
source = fopen(source_file, "r");
if (source == NULL) {
printf("Press any key to exit...n");
exit(EXIT_FAILURE);
}
target = fopen(target_file, "w");
if (target == NULL) {
fclose(source);
printf("Press any key to exit...n");
exit(EXIT_FAILURE);
}
while ((ch = fgetc(source)) != EOF)
fputc(ch, target);
printf("File copied successfully.n");
fclose(source);
fclose(target);
return 0;
}
Dr Namita Parati
Merging the contents of two files
#include<stdio.h>
main()
{
FILE *fp,*fp1,*fp2;
int i;
char ch;
fp=fopen("mfile.txt","a");
if(fp==NULL)
{
printf("File could not be openedn");
exit(0);
}
fp1=fopen("file1.txt","r");
if(fp1==NULL)
{
printf("File could not be openedn");
exit(0);
}
while((ch=fgetc(fp1))!=EOF)
fputc(ch,fp);
fputc('n',fp);
fp2=fopen("file2.txt","r");
if(fp2==NULL)
{
printf("File could not be openedn");
exit(0);
}
while((ch=fgetc(fp2))!=EOF)
fputc(ch,fp);
fclose(fp2);
fclose(fp1);
fclose(fp);
}
Dr Namita Parati
Command Line arguments
Dr Namita Parati
Dr Namita Parati

More Related Content

PDF
EASY UNDERSTANDING OF FILES IN C LANGUAGE.pdf
PPTX
File management
PDF
VIT351 Software Development VI Unit5
PDF
Unit 5 File handling in C programming.pdf
PPTX
Linux System Programming - Buffered I/O
PPTX
files c programming handling in computer programming
PDF
637225560972186380.pdf
PPTX
UNIT 10. Files and file handling in C
EASY UNDERSTANDING OF FILES IN C LANGUAGE.pdf
File management
VIT351 Software Development VI Unit5
Unit 5 File handling in C programming.pdf
Linux System Programming - Buffered I/O
files c programming handling in computer programming
637225560972186380.pdf
UNIT 10. Files and file handling in C

Similar to file_c.pdf (20)

PPTX
File Handling
PPTX
File Handling
PPTX
COM1407: File Processing
PPTX
Programming in C Session 4
PPTX
MODULE 8-File and preprocessor.pptx for c program learners easy learning
PPT
new pdfrdfzdfzdzzzzzzzzzzzzzzzzzzzzzzzzzzgggggggggggggggggggggggggggggggggggg...
PPT
How to do file-handling - in C language
PDF
FILES IN C
PPSX
File mangement
PPTX
Basics of file handling
PPTX
basics of file handling
PPTX
INput output stream in ccP Full Detail.pptx
DOCX
PDF
File handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reuge
PPTX
File management
PPT
file_handling_in_c.ppt
PPTX
PPS-II UNIT-5 PPT.pptx
PPTX
File handling in C hhsjsjshsjjsjsjs.pptx
PPTX
file_handling_python_bca_computer_python
File Handling
File Handling
COM1407: File Processing
Programming in C Session 4
MODULE 8-File and preprocessor.pptx for c program learners easy learning
new pdfrdfzdfzdzzzzzzzzzzzzzzzzzzzzzzzzzzgggggggggggggggggggggggggggggggggggg...
How to do file-handling - in C language
FILES IN C
File mangement
Basics of file handling
basics of file handling
INput output stream in ccP Full Detail.pptx
File handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reuge
File management
file_handling_in_c.ppt
PPS-II UNIT-5 PPT.pptx
File handling in C hhsjsjshsjjsjsjs.pptx
file_handling_python_bca_computer_python
Ad

More from Osmania University (15)

PPT
Introduction To Object Oriented language
PPTX
A person with an analytical mind is able.
PPTX
c programming lab for first year student
PPT
File handling in C is th process in read
PPT
Dos_Commands.ppt
PDF
Students Arsama Brochure (15 × 10 in).pdf
PPT
PreProcessorDirective.ppt
PPT
pointers (1).ppt
PDF
introds_110116.pdf
PDF
vmls-slides.pdf
PPT
CN Jntu PPT
PPT
Unit-INP.ppt
Introduction To Object Oriented language
A person with an analytical mind is able.
c programming lab for first year student
File handling in C is th process in read
Dos_Commands.ppt
Students Arsama Brochure (15 × 10 in).pdf
PreProcessorDirective.ppt
pointers (1).ppt
introds_110116.pdf
vmls-slides.pdf
CN Jntu PPT
Unit-INP.ppt
Ad

Recently uploaded (20)

PPTX
CT Generations and Image Reconstruction methods
PDF
SEH5E Unveiled: Enhancements and Key Takeaways for Certification Success
PDF
Unit I -OPERATING SYSTEMS_SRM_KATTANKULATHUR.pptx.pdf
PPTX
Wireless sensor networks (WSN) SRM unit 2
PDF
UEFA_Embodied_Carbon_Emissions_Football_Infrastructure.pdf
PPTX
Cisco Network Behaviour dibuywvdsvdtdstydsdsa
PDF
Principles of operation, construction, theory, advantages and disadvantages, ...
PPTX
Solar energy pdf of gitam songa hemant k
DOCX
ENVIRONMENTAL PROTECTION AND MANAGEMENT (18CVL756)
PDF
Project_Mgmt_Institute_-Marc Marc Marc .pdf
PPTX
WN UNIT-II CH4_MKaruna_BapatlaEngineeringCollege.pptx
PDF
VTU IOT LAB MANUAL (BCS701) Computer science and Engineering
PPTX
Micro1New.ppt.pptx the main themes if micro
PPTX
Agentic Artificial Intelligence (Agentic AI).pptx
PDF
Micro 4 New.ppt.pdf a servay of cells and microorganism
PPTX
Environmental studies, Moudle 3-Environmental Pollution.pptx
PDF
Research on ultrasonic sensor for TTU.pdf
PDF
UEFA_Carbon_Footprint_Calculator_Methology_2.0.pdf
PDF
AIGA 012_04 Cleaning of equipment for oxygen service_reformat Jan 12.pdf
PPTX
Design ,Art Across Digital Realities and eXtended Reality
CT Generations and Image Reconstruction methods
SEH5E Unveiled: Enhancements and Key Takeaways for Certification Success
Unit I -OPERATING SYSTEMS_SRM_KATTANKULATHUR.pptx.pdf
Wireless sensor networks (WSN) SRM unit 2
UEFA_Embodied_Carbon_Emissions_Football_Infrastructure.pdf
Cisco Network Behaviour dibuywvdsvdtdstydsdsa
Principles of operation, construction, theory, advantages and disadvantages, ...
Solar energy pdf of gitam songa hemant k
ENVIRONMENTAL PROTECTION AND MANAGEMENT (18CVL756)
Project_Mgmt_Institute_-Marc Marc Marc .pdf
WN UNIT-II CH4_MKaruna_BapatlaEngineeringCollege.pptx
VTU IOT LAB MANUAL (BCS701) Computer science and Engineering
Micro1New.ppt.pptx the main themes if micro
Agentic Artificial Intelligence (Agentic AI).pptx
Micro 4 New.ppt.pdf a servay of cells and microorganism
Environmental studies, Moudle 3-Environmental Pollution.pptx
Research on ultrasonic sensor for TTU.pdf
UEFA_Carbon_Footprint_Calculator_Methology_2.0.pdf
AIGA 012_04 Cleaning of equipment for oxygen service_reformat Jan 12.pdf
Design ,Art Across Digital Realities and eXtended Reality

file_c.pdf

  • 2. Why File Handling in C? • Permanent Storage: File handling allows the program to store data persistently. • Data Sharing: File handling enables data to be shared between different programs. • Large Data: File handling is ideal for dealing with large amounts of data. • Data Backup: File handling provides a way to create backups of important data. Dr Namita Parati
  • 3. STREAMS IN C • In C, the standard streams are termed as pre-connected input and output channels between a text terminal and the program (when it begins execution).Therefore, stream is a logical interface to the devices that are connected to the computer. • Stream is widely used as a logical interface to a file where a file can refer to a disk file, the computer screen, keyboard, etc. Although files may differ in the form and capabilities, all streams are the same. • The three standard streams in C languages are- • standard input (stdin), standard output (stdout) and standard error (stderr). Dr Namita Parati
  • 5. STREAMS IN C contd. • Standard input (stdin): Standard input is the stream from which the program receives its data. The program requests transfer of data using the read operation. However, not all programs require input. Generally, unless redirected, input for a program is expected from the keyboard. • Standard output (stdout): Standard output is the stream where a program writes its output data. The program requests data transfer using the write operation. However, not all programs generate output. • Standard error (stderr): Standard error is basically an output stream used by programs to report error messages or diagnostics. It is a stream independent of standard output and can be redirected separately. No doubt, the standard output and standard error can also be directed to the same destination. • A stream is linked to a file using an open operation and disassociated from a file using a close operation. KEYBOARD PROGRAM SCREEN stdin stderr stdout Dr Namita Parati
  • 6. BUFFER ASSOCIATED WITH FILE STREAM • When a stream linked to a disk file is created, a buffer is automatically created and associated with the stream. A buffer is nothing but a block of memory that is used for temporary storage of data that has to be read from or written to a file. • Buffers are needed because disk drives are block oriented devices as they can operate efficiently when data has to be read/ written in blocks of certain size. The size of ideal buffer size is hardware dependant. • The buffer acts as an interface between the stream (which is character-oriented) and the disk hardware (which is block oriented). When the program has to write data to the stream, it is saved in the buffer till it is full. Then the entire contents of the buffer are written to the disk as a block. PROGRAM BUFFER DISK Program writes data to buffer Data from the buffer is written to the disk file Similarly, when reading data from a disk file, the data is read as a block from the file and written into the buffer. The program reads data from the buffer. The creation and operation of the buffer is automatically handled by the operating system. However, C provides some functions for buffer manipulation. The data resides in the buffer until the buffer is flushed or written to a file. Dr Namita Parati
  • 7. Difference between Text File and Binary File Text File Binary File It contains alphabets and numbers which are easily understood by human beings. It contains 1’s and 0’s, which are easily understood by computers. An error in a text file can be eliminated when seen. The error in a binary file corrupts the file and is not easy to detect. Can store only plain text in a file. Can store different types of data (image, audio, text) in a single file. Widely used file format and can be opened using any simple text editor. Developed especially for an application and may not be understood by other applications. Mostly .txt is used as extensions to text files. Can have any application defined extension. Dr Namita Parati
  • 8. Files can be accessed in 2 ways • Sequential Access It is the simplest access method. Information in the file is processed in order, one after the other. • Direct Access (Random Access) Another method is direct access method also known as relative access method. A filed-length logical record that allows the program to read and write record randomly in no particular order. Dr Namita Parati
  • 9. Sequential Versus Random Access Dr Namita Parati
  • 11. File handling operations • File handling in C allows 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. • Creation of the new file • Opening an existing file • Reading from the file • Writing to the file • Deleting the file Dr Namita Parati
  • 12. 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 fputs() writes a string to file 7 fgets() reads a string from file 8 fclose() closes the file 9 fseek() sets the file pointer to given position 10 ftell() returns current position 11 rewind() sets the file pointer to the beginning of the file Dr Namita Parati
  • 14. Random Access Functions Dr Namita Parati
  • 15. 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. • FILE *fopen( const char * filename, const char * mode ); Dr Namita Parati
  • 16. • The fopen() function accepts two parameters: • 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". • The mode in which the file is to be opened. It is a string. Dr Namita Parati
  • 17. We can use one of the following modes in the fopen() function. 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 Dr Namita Parati
  • 18. The fopen function works in the following way. • Firstly, It searches the file to be opened. • Then, it loads the file from the disk and place it into the buffer. The buffer is used to provide efficiency for the read operations. • It sets up a character pointer which points to the first character of the file. Dr Namita Parati
  • 19. fopen() example // C program to illustrate fopen() #include <stdio.h> #include <stdlib.h> main() { // pointer demo to FILE FILE* fp; // Creates a file "demo_file" // with file acccess as write-plus mode fp = fopen("demo_file.txt", "w+"); // adds content to the file fprintf(demo, "%s %s %s", "Welcome", "to", “MVSR"); // closes the file pointed by fp fclose(fp); } a new file will be created by the name “demo_file” and with the following content: Welcome to MVSR Dr Namita Parati
  • 20. Example2 Reading Char by Char from a file #include<stdio.h> void main( ) { FILE *fp ; char ch ; fp = fopen(“hello.c","r") ; //use existing file name while ( 1 ) { ch = fgetc ( fp ) ; if ( ch == EOF ) break ; printf("%c",ch) ; } fclose (fp ) ; } Dr Namita Parati
  • 21. 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 ); Dr Namita Parati
  • 22. fprintf() function • The fprintf() function is used to write set of characters into file. It sends formatted output to a stream. #include <stdio.h> main(){ FILE *fp; fp = fopen("file.txt", "w");//opening file fprintf(fp, "Hello file by fprintf...n");//writing data into file fclose(fp);//closing file } Dr Namita Parati
  • 23. 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. #include <stdio.h> main(){ FILE *fp; char buff[255];//creating char array to store data of file fp = fopen("file.txt", "r"); while(fscanf(fp, "%s", buff)!=EOF){ printf("%s ", buff ); } fclose(fp); } Output: Hello file by fprintf... Dr Namita Parati
  • 24. C File Example: Storing employee information • file handling example to store employee information as entered by user from console. • We are going to store id, name and salary of the employee. #include <stdio.h> void main() { FILE *fptr; int id; char name[30]; float salary; fptr = fopen("emp.txt", "w+");/* open for writing */ if (fptr == NULL) { printf("File does not exists n"); return; } Dr Namita Parati
  • 25. printf("Enter the idn"); scanf("%d", &id); fprintf(fptr, "Id= %dn", id); printf("Enter the name n"); scanf("%s", name); fprintf(fptr, "Name= %sn", name); printf("Enter the salaryn"); scanf("%f", &salary); fprintf(fptr, "Salary= %.2fn", salary); fclose(fptr); } Output: Enter the id 1 Enter the name Ravi Enter the salary 120000 Dr Namita Parati
  • 26. Now open file from current directory. you will see emp.txt file. It will have following information. emp.txt Id= 1 Name= Ravi Salary= 120000 Dr Namita Parati
  • 27. fputc() function • The fputc() function is used to write a single character into file. • It outputs a character to a stream. #include <stdio.h> main(){ FILE *fp; fp = fopen("file1.txt", "w");//opening file fputc('a',fp);//writing single character into file fclose(fp);//closing file } file1.txt a Dr Namita Parati
  • 28. 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. #include<stdio.h> void main(){ FILE *fp; char c; fp=fopen("myfile.txt","r"); while((c=fgetc(fp))!=EOF) { printf("%c",c); } fclose(fp); } Dr Namita Parati
  • 29. fputs() function • The fputs() function writes a line of characters into file. It outputs string to a stream. #include<stdio.h> void main(){ FILE *fp; fp=fopen("myfile2.txt","w"); fputs("hello c programming",fp); fclose(fp); } Dr Namita Parati
  • 30. fgets() function • The fgets() function reads a line of characters from file. It gets string from a stream. #include<stdio.h> void main(){ FILE *fp; char text[300]; fp=fopen("myfile2.txt","r"); printf("%s",fgets(text,200,fp)); fclose(fp); } Dr Namita Parati
  • 31. fseek() function • The fseek() function is used to set the file pointer to the specified offset(address). It is used to write data into file at desired location. #include <stdio.h> void main(){ FILE *fp; fp = fopen("myfile.txt","w+"); fputs("This is last unit", fp); fseek( fp, 7, SEEK_SET ); fputs(“important", fp); fclose(fp); } myfile.txt This is important Dr Namita Parati
  • 32. rewind() function • The rewind() function sets the file pointer at the beginning of the stream. It is useful if you have to use stream many times. #include<stdio.h> void main(){ FILE *fp; char c; fp=fopen("file.txt","r"); Dr Namita Parati
  • 33. while((c=fgetc(fp))!=EOF){ printf("%c",c); } rewind(fp);//moves the file pointer at beginning of the file while((c=fgetc(fp))!=EOF){ printf("%c",c); } fclose(fp); } Output: this is a simple textthis is a simple text Dr Namita Parati
  • 34. ftell() function • The ftell() function returns the current file position of the specified stream. We can use ftell() function to get the total size of a file after moving file pointer at the end of file. #include <stdio.h> void main (){ FILE *fp; int length; clrscr(); fp = fopen("file.txt", "r"); fseek(fp, 0, SEEK_END); length = ftell(fp); fclose(fp); printf("Size of file: %d bytes", length); } Output: Size of file: 21 bytes Dr Namita Parati
  • 35. C program to copy the contents of one file to another file #include <iostream> #include <stdlib.h> int main() { char ch;// source_file[20], target_file[20]; FILE *source, *target; char source_file[]="x1.txt"; char target_file[]="x2.txt"; source = fopen(source_file, "r"); if (source == NULL) { printf("Press any key to exit...n"); exit(EXIT_FAILURE); } target = fopen(target_file, "w"); if (target == NULL) { fclose(source); printf("Press any key to exit...n"); exit(EXIT_FAILURE); } while ((ch = fgetc(source)) != EOF) fputc(ch, target); printf("File copied successfully.n"); fclose(source); fclose(target); return 0; } Dr Namita Parati
  • 36. Merging the contents of two files #include<stdio.h> main() { FILE *fp,*fp1,*fp2; int i; char ch; fp=fopen("mfile.txt","a"); if(fp==NULL) { printf("File could not be openedn"); exit(0); } fp1=fopen("file1.txt","r"); if(fp1==NULL) { printf("File could not be openedn"); exit(0); } while((ch=fgetc(fp1))!=EOF) fputc(ch,fp); fputc('n',fp); fp2=fopen("file2.txt","r"); if(fp2==NULL) { printf("File could not be openedn"); exit(0); } while((ch=fgetc(fp2))!=EOF) fputc(ch,fp); fclose(fp2); fclose(fp1); fclose(fp); } Dr Namita Parati
  • 37. Command Line arguments Dr Namita Parati