SlideShare a Scribd company logo
FILES
Introduction to Files
So far, the operations using C program are done on a prompt / terminal
which is not stored anywhere. But in the software industry, most of the
programs are written to store the information fetched from the program.
One such way is to store the fetched information in a file. Different
operations that can be performed on a file are:
1. Creation of a new file
2. Opening an existing file
3. Reading from file
4. Writing to a file
5. Move the pointer to a specific location in a file
6. Closing a file
What is a File?
• A file can be treated as external storage. It consists of a sequence of bytes
residing on the disk.
• A program can create, read, and write into a file. Unlike an array, the data
in the file is retained even after the program finishes its execution. It's a
permanent storage medium.
• File handling in C programming uses FILE STREAM as a means of
communication between programs and data files.
• The INPUT STREAM extracts the data from the files and supplies it to the
program.
• The OUTPUT STREAM stores the data into the file supplied by the program.
• C uses a structure called FILE (defined in stdio.h) to store the attributes of a
file.
Declaring a File Pointer
• In C language, in order to declare a file, we use a file pointer. A file
pointer is a pointer variable that specifies the next byte to be read or
written to.
• Every time a file is opened, the file pointer points to the beginning of
the file. A file is declared as follows:
• FILE *fp;
• //fp is the name of the file pointer
The basic File operations
 Open a file
 Read data from a file
 Write data into a file
 Close a file
Library 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()
• The fopen() function is used to open a file. The syntax of the fopen() is
given below.
• fp = FILE *fopen(const char *filename, const char *mode);
• fp is the file pointer that holds the reference to the file, the filename is
the name of the file to be opened or created, and mode specifies the
purpose of opening a file such as for reading or writing.
• FILE is an object type used for storing information about the file
stream.
Opening File: fopen()
• A file can be opened in
different modes. Below
are some of the most
commonly used modes for
opening or creating a file.
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
#include<stdio.h>
void main( )
{
FILE *fp ;
char ch ;
fp = fopen("file_handle.c","r") ;
while ( 1 )
{
ch = fgetc ( fp ) ;
if ( ch == EOF )
break ;
printf("%c",ch) ;
}
fclose (fp ) ;
}
Opening File: fopen()
• A file needs to be closed after a read or write operation to release the
memory allocated by the program.
• In C, a file is closed using the fclose() function.
• This returns 0 on success and EOF in the case of a failure.
• An EOF is defined in the library called stdio.h.
• EOF is a constant defined as a negative integer value which denotes
that the end of the file has reached.
Syntax: fclose( FILE *fp );
Closing File: fclose()
Writing and Reading Functions
1. getc(): Read a single character from the opened file
2. putc(): Write a single character from the opened file
3. fgetc(): Reads a character from the file with the help of the file pointer fp. It returns EOF at
the end of the file
4. fputc(): Writes a character into the file with the help of the file pointer fp. It returns EOF in
the case of an error
5. fgets(): Read a line of message from the file.
6. fputs(): Write’s a line of message into the file.
7. fprintf(): It sends formatted output to a stream.
8. fscanf(): It reads formatted data from the stream.
9. putw(): Write’s an integer data into a file.
10.getw(): Read integer data from the file.
getc(): Read a single character
getc():
This function reads a single character from the opened file and moves
the file pointer. It returns EOF if end of file reached.
Syntax: char ch=getc(fp);
It is available in conio.h
#include<stdio.h>
#include<conio.h>
void main()
{
FILE *f;
char c;
f = fopen(“list.txt”, “r”);
if(f == NULL)
ptintf(“File not find”);
else
while(c = getc(f)) != EOF)
printf(“%c”,c);
fclose(f);
}
getc(): Example
putc(): Write a single character
putc():
This function is used to write a single character into a file. If an error
occurs it returns EOF.
Syntax: putc( ch, Fp );
‘Fp’ indicates File pointer.
#include<stdio.h>
#include<conio.h>
void main()
{
FILE *f;
char c;
ptintf(“Enter few words and ‘*’ to exit”);
f = fopen(“words.txt”, “w”);
while( (c = getchar()) != ‘*’ )
putc(c , f);
fclose(f);
}
putc(): Example
fputc(): Write a single character
fputc():
This function writes a character c into the file with the help of the file
pointer fp. It returns EOF in the case of an error.
Syntax: int fputc( int c, FILE *fp );
#include<stdio.h>
#include<conio.h>
void main()
{
FILE *fp;
fp = fopen("file1.txt", "w");//opening file
fputc('a',fp);//writing single character into file
fclose(fp);
}
fputc(): Example
fgetc(): Read a single character
fgetc():
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: int fgetc(FILE *fp)
#include<stdio.h>
#include<conio.h>
void main()
{
FILE *fp;
char c;
fp=fopen("myfile.txt","r");
while((c=fgetc(fp))!=EOF)
printf("%c",c);
fclose(fp);
}
fgetc(): Example
fputs() and fgets()
The fputs() and fgets() in C programming are used to write and read
string from stream
fputs():
The fputs() function writes a line of characters into file. It outputs string
to a stream.
Syntax: int fputs( const char *s, FILE *fp );
This function writes string s to the file with the help of the reference
pointer fp.
#include<stdio.h>
#include<conio.h>
void main()
{
FILE *fp;
fp=fopen("myfile2.txt","w");
fputs("hello c programming",fp);
fclose(fp);
}
fputs(): Example
fputs() and fgets()
fgets():
The fgets() function reads a line of characters from file. It gets string
from a stream.
Syntax: char *fgets( char *buffer, int n, FILE *fp );
fgets() reads up to n characters from the input stream referenced by fp.
The string reads and copied into the character buffer and terminates
when a null character is encountered.
#include<stdio.h>
#include<conio.h>
void main()
{
FILE *fp;
char text[300];
fp=fopen("myfile2.txt","r");
printf("%s",fgets(text,200,fp));
fclose(fp);
}
fgets(): Example
fprintf() and fscanf()
fprintf():
The fprintf() function is used to write set of characters into file. It sends
formatted output to a stream.
Syntax: int fprintf(FILE *fp, const char *format)
#include<stdio.h>
#include<conio.h>
void main()
{
FILE *fp;
fp = fopen("file.txt", "w");//opening file
fprintf(fp, "Hello file by fprintf...n");//writing data into file
fclose(fp);
}
fprintf(): Example
fprintf() and fscanf()
fscanf():
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: int fscanf(FILE *fp, const char *format , ..)
#include<stdio.h>
#include<conio.h>
void 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);
}
fscanf(): Example
#include<stdio.h>
#include<conio.h>
void main()
{
FILE *fptr;
int id;
char name[30];
float salary;
fptr = fopen("emp.txt", "w+");
if (fptr == NULL)
{
printf("File does not exists n");
return 0;
}
fscanf(): Example
#include<stdio.h>
#include<conio.h>
void main()
{
FILE *fptr;
int id;
char name[30];
float salary;
fptr = fopen("emp.txt", "w+");
if (fptr == NULL)
{
printf("File does not exists n");
return 0;
}
Hold employee information in to a File
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);
}
getw() and putw()
putw():
This function is used to write an integer value to file. This function
deals with integer data only.
Syntax: putw( int v, FILE *FP);
getw():
This function returns the integer value from a file and increments the
file pointer. This function deals with only integers.
Syntax: int getw( FILE *FP );
Block Input and Output
• It is important to know how numerical data is stored on the disk by fprintf() function.
• Text and characters requires one byte for storing them with fprintf(). Similarly for storing
numbers in memory two bytes and for floats four bytes.
• For example 3456 occupies two bytes in memory. But when it is transferred to the disk
file using fprint() function it would occupies four bytes. For each character it
requires one byte. Even for float also each digit including dot(.) requires one byte.
• Thus large amount of integers and float data requires large space on the disk. To
overcome this problem files should be read and write in binary mode, for which we use
fread() and fwrite() functions.
• fwrite(): This function is used for writing an entire structure block to a given file.
• fread(): This function is used for reading an entire block from a given file.
#include<stdio.h>
#include<conio.h>
void main()
{
struct
{
char name[20];
int age;
}stud[50],s1[50];
FILE *fp;
int i, j=0, n;
char str[15];
printf(“Enter File Name:”);
scanf(“%s”,str);
fp = fopen(str, “rb”);
if( fp == NULL)
puts(“File does not exist”);
Block Input and Output
else
{
puts(“How many records:”);
scanf(“%d”, &n);
for(i=0;i<n;i++)
{
puts(“Name:” );
scanf(“%s”, &stud[i].name);
puts(“Age:” );
scanf(“%s”, &stud[i].age);
}
j=n;
while(n !=0 )
{
fwrite(&stud, sizeof(stud), 1, fp);
n--;
}
Block Input and Output
for(i=0; i<j ; i++ )
{
fread(&s1, sizeof(s1), 1, fp);
printf(“Name %s t Age %d n”, s1[i].name, s1[i].age);
}
}//else close
fclose(fp);
}//main close
Block Input and Output
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: int fseek(FILE *stream, long int offset, int position)
Three are arguments are to be passed through this function. They are:
1. File pointer
2. Offset: offset may be positive (moving in forward from current position) or negative (moving
backwards). The offset being a variable of type long.
3. The current position of file pointer.
• There are 3 constants used in the fseek() function for position: SEEK_SET, SEEK_CUR and
SEEK_END
Integer
value
Constant Location in the File
0 SEEK_SET Beginning of the file
1 SEEK_CUR Current position of the file pointer
2 SEEK_END End of the file
#include <stdio.h>
void main(){
FILE *fp;
fp = fopen("myfile.txt","w+");
fputs("This is a C program", fp);
fseek( fp, 7, SEEK_SET );
fputs("File handling in C", fp);
fclose(fp);
}
fseek() Example
myfile.txt
This is File handling in C
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.
Syntax: void rewind(FILE *stream)
Example:
File: file.txt
this is a simple text
File Name: rewind.c
#include<stdio.h>
void main(){
FILE *fp;
char c;
fp=fopen("file.txt","r");
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);
}
rewind() Example
File: file.txt
this is a simple text
Output:
this is a simple textthis is a simple text
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.
• We can use SEEK_END constant to move the file pointer at the end of file.
Syntax: long int ftell(FILE *stream)
File Name: ftell.c
#include <stdio.h>
void main (){
FILE *fp;
int length;
fp = fopen("file.txt", "r");
fseek(fp, 0, SEEK_END);
length = ftell(fp);
fclose(fp);
printf("Size of file: %d bytes", length);
}
ftell() Example
File: file.txt
this is a simple text
Output:
Size of file: 21 bytes
want to learn files,then just use this ppt to learn

More Related Content

PDF
EASY UNDERSTANDING OF FILES IN C LANGUAGE.pdf
PPTX
File handling in c
PDF
Advance C Programming UNIT 4-FILE HANDLING IN C.pdf
PPTX
File Handling ppt.pptx shjd dbkd z bdjdb d
PPTX
File management
PPTX
File in C language
PPTX
Programming C- File Handling , File Operation
PDF
File Handling in C Programming
EASY UNDERSTANDING OF FILES IN C LANGUAGE.pdf
File handling in c
Advance C Programming UNIT 4-FILE HANDLING IN C.pdf
File Handling ppt.pptx shjd dbkd z bdjdb d
File management
File in C language
Programming C- File Handling , File Operation
File Handling in C Programming

Similar to want to learn files,then just use this ppt to learn (20)

PPTX
PPS PPT 2.pptx
PPTX
files c programming handling in computer programming
PPTX
pre processor and file handling in c language ppt
PDF
VIT351 Software Development VI Unit5
PPTX
MODULE 8-File and preprocessor.pptx for c program learners easy learning
PPTX
C-Programming File-handling-C.pptx
PPTX
C-Programming File-handling-C.pptx
PPT
PPT
File management and handling by prabhakar
PPT
C-Programming Chapter 5 File-handling-C.ppt
PPT
C-Programming Chapter 5 File-handling-C.ppt
PPSX
File mangement
PPTX
C Programming Unit-5
PPSX
1file handling
DOCX
Understanding c file handling functions with examples
PPTX
File Handling in C Programming for Beginners
PPT
How to do file-handling - in C language
PDF
637225560972186380.pdf
PPTX
File handling in c Programming - Unit 5.1
PPS PPT 2.pptx
files c programming handling in computer programming
pre processor and file handling in c language ppt
VIT351 Software Development VI Unit5
MODULE 8-File and preprocessor.pptx for c program learners easy learning
C-Programming File-handling-C.pptx
C-Programming File-handling-C.pptx
File management and handling by prabhakar
C-Programming Chapter 5 File-handling-C.ppt
C-Programming Chapter 5 File-handling-C.ppt
File mangement
C Programming Unit-5
1file handling
Understanding c file handling functions with examples
File Handling in C Programming for Beginners
How to do file-handling - in C language
637225560972186380.pdf
File handling in c Programming - Unit 5.1
Ad

Recently uploaded (20)

PPTX
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
PDF
Supply Chain Operations Speaking Notes -ICLT Program
PPTX
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
PPTX
Cell Types and Its function , kingdom of life
PDF
Pre independence Education in Inndia.pdf
PPTX
PPH.pptx obstetrics and gynecology in nursing
PPTX
master seminar digital applications in india
PPTX
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
PPTX
Microbial diseases, their pathogenesis and prophylaxis
PDF
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
PDF
102 student loan defaulters named and shamed – Is someone you know on the list?
PDF
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
PDF
O5-L3 Freight Transport Ops (International) V1.pdf
PDF
Module 4: Burden of Disease Tutorial Slides S2 2025
PPTX
Renaissance Architecture: A Journey from Faith to Humanism
PDF
01-Introduction-to-Information-Management.pdf
PDF
2.FourierTransform-ShortQuestionswithAnswers.pdf
PDF
Abdominal Access Techniques with Prof. Dr. R K Mishra
PDF
Classroom Observation Tools for Teachers
PDF
FourierSeries-QuestionsWithAnswers(Part-A).pdf
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
Supply Chain Operations Speaking Notes -ICLT Program
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
Cell Types and Its function , kingdom of life
Pre independence Education in Inndia.pdf
PPH.pptx obstetrics and gynecology in nursing
master seminar digital applications in india
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
Microbial diseases, their pathogenesis and prophylaxis
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
102 student loan defaulters named and shamed – Is someone you know on the list?
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
O5-L3 Freight Transport Ops (International) V1.pdf
Module 4: Burden of Disease Tutorial Slides S2 2025
Renaissance Architecture: A Journey from Faith to Humanism
01-Introduction-to-Information-Management.pdf
2.FourierTransform-ShortQuestionswithAnswers.pdf
Abdominal Access Techniques with Prof. Dr. R K Mishra
Classroom Observation Tools for Teachers
FourierSeries-QuestionsWithAnswers(Part-A).pdf
Ad

want to learn files,then just use this ppt to learn

  • 2. Introduction to Files So far, the operations using C program are done on a prompt / terminal which is not stored anywhere. But in the software industry, most of the programs are written to store the information fetched from the program. One such way is to store the fetched information in a file. Different operations that can be performed on a file are: 1. Creation of a new file 2. Opening an existing file 3. Reading from file 4. Writing to a file 5. Move the pointer to a specific location in a file 6. Closing a file
  • 3. What is a File? • A file can be treated as external storage. It consists of a sequence of bytes residing on the disk. • A program can create, read, and write into a file. Unlike an array, the data in the file is retained even after the program finishes its execution. It's a permanent storage medium. • File handling in C programming uses FILE STREAM as a means of communication between programs and data files. • The INPUT STREAM extracts the data from the files and supplies it to the program. • The OUTPUT STREAM stores the data into the file supplied by the program. • C uses a structure called FILE (defined in stdio.h) to store the attributes of a file.
  • 4. Declaring a File Pointer • In C language, in order to declare a file, we use a file pointer. A file pointer is a pointer variable that specifies the next byte to be read or written to. • Every time a file is opened, the file pointer points to the beginning of the file. A file is declared as follows: • FILE *fp; • //fp is the name of the file pointer
  • 5. The basic File operations  Open a file  Read data from a file  Write data into a file  Close a file
  • 6. Library 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
  • 7. Opening File: fopen() • The fopen() function is used to open a file. The syntax of the fopen() is given below. • fp = FILE *fopen(const char *filename, const char *mode); • fp is the file pointer that holds the reference to the file, the filename is the name of the file to be opened or created, and mode specifies the purpose of opening a file such as for reading or writing. • FILE is an object type used for storing information about the file stream.
  • 8. Opening File: fopen() • A file can be opened in different modes. Below are some of the most commonly used modes for opening or creating a file. 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
  • 9. #include<stdio.h> void main( ) { FILE *fp ; char ch ; fp = fopen("file_handle.c","r") ; while ( 1 ) { ch = fgetc ( fp ) ; if ( ch == EOF ) break ; printf("%c",ch) ; } fclose (fp ) ; } Opening File: fopen()
  • 10. • A file needs to be closed after a read or write operation to release the memory allocated by the program. • In C, a file is closed using the fclose() function. • This returns 0 on success and EOF in the case of a failure. • An EOF is defined in the library called stdio.h. • EOF is a constant defined as a negative integer value which denotes that the end of the file has reached. Syntax: fclose( FILE *fp ); Closing File: fclose()
  • 11. Writing and Reading Functions 1. getc(): Read a single character from the opened file 2. putc(): Write a single character from the opened file 3. fgetc(): Reads a character from the file with the help of the file pointer fp. It returns EOF at the end of the file 4. fputc(): Writes a character into the file with the help of the file pointer fp. It returns EOF in the case of an error 5. fgets(): Read a line of message from the file. 6. fputs(): Write’s a line of message into the file. 7. fprintf(): It sends formatted output to a stream. 8. fscanf(): It reads formatted data from the stream. 9. putw(): Write’s an integer data into a file. 10.getw(): Read integer data from the file.
  • 12. getc(): Read a single character getc(): This function reads a single character from the opened file and moves the file pointer. It returns EOF if end of file reached. Syntax: char ch=getc(fp); It is available in conio.h
  • 13. #include<stdio.h> #include<conio.h> void main() { FILE *f; char c; f = fopen(“list.txt”, “r”); if(f == NULL) ptintf(“File not find”); else while(c = getc(f)) != EOF) printf(“%c”,c); fclose(f); } getc(): Example
  • 14. putc(): Write a single character putc(): This function is used to write a single character into a file. If an error occurs it returns EOF. Syntax: putc( ch, Fp ); ‘Fp’ indicates File pointer.
  • 15. #include<stdio.h> #include<conio.h> void main() { FILE *f; char c; ptintf(“Enter few words and ‘*’ to exit”); f = fopen(“words.txt”, “w”); while( (c = getchar()) != ‘*’ ) putc(c , f); fclose(f); } putc(): Example
  • 16. fputc(): Write a single character fputc(): This function writes a character c into the file with the help of the file pointer fp. It returns EOF in the case of an error. Syntax: int fputc( int c, FILE *fp );
  • 17. #include<stdio.h> #include<conio.h> void main() { FILE *fp; fp = fopen("file1.txt", "w");//opening file fputc('a',fp);//writing single character into file fclose(fp); } fputc(): Example
  • 18. fgetc(): Read a single character fgetc(): 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: int fgetc(FILE *fp)
  • 19. #include<stdio.h> #include<conio.h> void main() { FILE *fp; char c; fp=fopen("myfile.txt","r"); while((c=fgetc(fp))!=EOF) printf("%c",c); fclose(fp); } fgetc(): Example
  • 20. fputs() and fgets() The fputs() and fgets() in C programming are used to write and read string from stream fputs(): The fputs() function writes a line of characters into file. It outputs string to a stream. Syntax: int fputs( const char *s, FILE *fp ); This function writes string s to the file with the help of the reference pointer fp.
  • 22. fputs() and fgets() fgets(): The fgets() function reads a line of characters from file. It gets string from a stream. Syntax: char *fgets( char *buffer, int n, FILE *fp ); fgets() reads up to n characters from the input stream referenced by fp. The string reads and copied into the character buffer and terminates when a null character is encountered.
  • 23. #include<stdio.h> #include<conio.h> void main() { FILE *fp; char text[300]; fp=fopen("myfile2.txt","r"); printf("%s",fgets(text,200,fp)); fclose(fp); } fgets(): Example
  • 24. fprintf() and fscanf() fprintf(): The fprintf() function is used to write set of characters into file. It sends formatted output to a stream. Syntax: int fprintf(FILE *fp, const char *format)
  • 25. #include<stdio.h> #include<conio.h> void main() { FILE *fp; fp = fopen("file.txt", "w");//opening file fprintf(fp, "Hello file by fprintf...n");//writing data into file fclose(fp); } fprintf(): Example
  • 26. fprintf() and fscanf() fscanf(): 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: int fscanf(FILE *fp, const char *format , ..)
  • 27. #include<stdio.h> #include<conio.h> void 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); } fscanf(): Example
  • 28. #include<stdio.h> #include<conio.h> void main() { FILE *fptr; int id; char name[30]; float salary; fptr = fopen("emp.txt", "w+"); if (fptr == NULL) { printf("File does not exists n"); return 0; } fscanf(): Example
  • 29. #include<stdio.h> #include<conio.h> void main() { FILE *fptr; int id; char name[30]; float salary; fptr = fopen("emp.txt", "w+"); if (fptr == NULL) { printf("File does not exists n"); return 0; } Hold employee information in to a File 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); }
  • 30. getw() and putw() putw(): This function is used to write an integer value to file. This function deals with integer data only. Syntax: putw( int v, FILE *FP); getw(): This function returns the integer value from a file and increments the file pointer. This function deals with only integers. Syntax: int getw( FILE *FP );
  • 31. Block Input and Output • It is important to know how numerical data is stored on the disk by fprintf() function. • Text and characters requires one byte for storing them with fprintf(). Similarly for storing numbers in memory two bytes and for floats four bytes. • For example 3456 occupies two bytes in memory. But when it is transferred to the disk file using fprint() function it would occupies four bytes. For each character it requires one byte. Even for float also each digit including dot(.) requires one byte. • Thus large amount of integers and float data requires large space on the disk. To overcome this problem files should be read and write in binary mode, for which we use fread() and fwrite() functions. • fwrite(): This function is used for writing an entire structure block to a given file. • fread(): This function is used for reading an entire block from a given file.
  • 32. #include<stdio.h> #include<conio.h> void main() { struct { char name[20]; int age; }stud[50],s1[50]; FILE *fp; int i, j=0, n; char str[15]; printf(“Enter File Name:”); scanf(“%s”,str); fp = fopen(str, “rb”); if( fp == NULL) puts(“File does not exist”); Block Input and Output
  • 33. else { puts(“How many records:”); scanf(“%d”, &n); for(i=0;i<n;i++) { puts(“Name:” ); scanf(“%s”, &stud[i].name); puts(“Age:” ); scanf(“%s”, &stud[i].age); } j=n; while(n !=0 ) { fwrite(&stud, sizeof(stud), 1, fp); n--; } Block Input and Output
  • 34. for(i=0; i<j ; i++ ) { fread(&s1, sizeof(s1), 1, fp); printf(“Name %s t Age %d n”, s1[i].name, s1[i].age); } }//else close fclose(fp); }//main close Block Input and Output
  • 35. 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: int fseek(FILE *stream, long int offset, int position) Three are arguments are to be passed through this function. They are: 1. File pointer 2. Offset: offset may be positive (moving in forward from current position) or negative (moving backwards). The offset being a variable of type long. 3. The current position of file pointer. • There are 3 constants used in the fseek() function for position: SEEK_SET, SEEK_CUR and SEEK_END Integer value Constant Location in the File 0 SEEK_SET Beginning of the file 1 SEEK_CUR Current position of the file pointer 2 SEEK_END End of the file
  • 36. #include <stdio.h> void main(){ FILE *fp; fp = fopen("myfile.txt","w+"); fputs("This is a C program", fp); fseek( fp, 7, SEEK_SET ); fputs("File handling in C", fp); fclose(fp); } fseek() Example myfile.txt This is File handling in C
  • 37. 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. Syntax: void rewind(FILE *stream) Example: File: file.txt this is a simple text
  • 38. File Name: rewind.c #include<stdio.h> void main(){ FILE *fp; char c; fp=fopen("file.txt","r"); 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); } rewind() Example File: file.txt this is a simple text Output: this is a simple textthis is a simple text
  • 39. 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. • We can use SEEK_END constant to move the file pointer at the end of file. Syntax: long int ftell(FILE *stream)
  • 40. File Name: ftell.c #include <stdio.h> void main (){ FILE *fp; int length; fp = fopen("file.txt", "r"); fseek(fp, 0, SEEK_END); length = ftell(fp); fclose(fp); printf("Size of file: %d bytes", length); } ftell() Example File: file.txt this is a simple text Output: Size of file: 21 bytes