22-File Handling-22-08-2023

You might also like

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 61

1

Dr.PoonGunDran,SENSE VIT, Vellore


2
Dr.PoonGunDran,SENSE VIT, Vellore
3
Dr.PoonGunDran,SENSE VIT, Vellore
4
Dr.PoonGunDran,SENSE VIT, Vellore
FILE HANDLING IN C:
• In programming, we may require some specific input data to
be generated several numbers of times. Sometimes, it is not
enough to only display the data on the console.
• The data to be displayed may be very large, and only a
limited amount of data can be displayed on the console, and
since the memory is volatile, it is impossible to recover the
programmatically generated data again and again.
• However, if we need to do so, we may store it onto the local
file system which is volatile and can be accessed every
time. Here, comes the need of file handling in C.

5
Dr.PoonGunDran,SENSE VIT, Vellore
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 a new file (fopen with attributes as “a” or
“a+” or “w” or “w++”)
2.Opening an existing file (fopen)
3.Reading from file (fscanf or fgets)
4.Writing to a file (fprintf or fputs)
5.Moving to a specific location in a file (fseek, rewind)
6.Closing a file (fclose)

6
Dr.PoonGunDran,SENSE VIT, Vellore
7
Dr.PoonGunDran,SENSE VIT, Vellore
FUNCTIONS FOR FILE HANDLING

8
Dr.PoonGunDran,SENSE VIT, Vellore
9
Dr.PoonGunDran,SENSE VIT, Vellore
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.

10
Dr.PoonGunDran,SENSE VIT, Vellore
OPENING FILE: fopen()
The syntax of the fopen() is given below

FILE *fopen( const char * filename, const char * mode );

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.
• The mode in which the file is to be opened. It is a string.

11
Dr.PoonGunDran,SENSE VIT, Vellore
READING FROM A FILE –
The file read operations can be performed using functions
fscanf or fgets. Both the functions performed the same
operations as that of scanf and gets but with an additional
parameter, the file pointer.

FILE * filePointer;
filePointer = fopen(“fileName.txt”, “r”);
fscanf(filePointer, "%s %s %s %d", str1, str2, str3, &year);

12
Dr.PoonGunDran,SENSE VIT, Vellore
WRITING FILE : FPRINTF() FUNCTION
The fprintf() function is used to write set of characters
into file. It sends formatted output to a stream.

Syntax:
int fprintf (FILE *stream, const char *format

[, argument, ...] )

13
Dr.PoonGunDran,SENSE VIT, Vellore
WRITING A FILE –:

The file write operations can be perfomed by the


functions fprintf and fputs with similarities to read
operations.

FILE *filePointer ;
filePointer = fopen(“fileName.txt”, “w”);
fprintf(filePointer, "%s %s %s %d", "We", "are",
"in", 2021);

14
Dr.PoonGunDran,SENSE VIT, Vellore
CLOSING A FILE
After every successful fie operations, you must
always close a file. For closing a file, you have
to use fclose function.
FILE *filePointer ;
filePointer= fopen(“fileName.txt”, “w”);
---------- Some file Operations -------
fclose(filePointer)

15
Dr.PoonGunDran,SENSE VIT, Vellore
WRITING FILE : FPRINTF() FUNCTION

#include <stdio.h>
void main(){
FILE *fp;
fp = fopen("filex.txt", "w");//opening file
fprintf(fp, "Hello file by fprintf...\n");//writing data
fclose(fp);//closing file
}

16
Dr.PoonGunDran,SENSE VIT, Vellore
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:
int fscanf(FILE *stream, const char *format
[, argument, ...])

17
Dr.PoonGunDran,SENSE VIT, Vellore
READING FILE :
FSCANF() FUNCTION
#include <stdio.h>
void main(){
FILE *fp;
char buff[255];//
creating char array to store data of file
fp = fopen(“123testpoong.txt", "r");
while(fscanf(fp, "%s", buff)!=EOF){
printf("%s ", buff );
}
fclose(fp);

18
Dr.PoonGunDran,SENSE VIT, Vellore
C fprintf() and fscanf()

19
Dr.PoonGunDran,SENSE VIT, Vellore
WRITING FILE : FPRINTF()
FUNCTION
The fprintf() function is used to write set of
characters into file. It sends formatted output
to a stream.

Syntax:
int fprintf(FILE *stream, const char *format
[, argument, ...])

20
Dr.PoonGunDran,SENSE VIT, Vellore
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:
int fscanf(FILE *stream, const char *format
[, argument, ...])

21
Dr.PoonGunDran,SENSE VIT, Vellore
C FPUTC() AND FGETC()

22
Dr.PoonGunDran,SENSE VIT, Vellore
FPUTC() FUNCTION
The fputc() function is used to write a
single character into file. It outputs a
character to a stream.
Syntax:
int fputc(int c, FILE *stream)

23
Dr.PoonGunDran,SENSE VIT, Vellore
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:
int fgetc(FILE *stream)

24
Dr.PoonGunDran,SENSE VIT, Vellore
C fputs() and fgets()

25
Dr.PoonGunDran,SENSE VIT, Vellore
C FPUTS()
• The fputs() in C programming are used to
write and read string from stream. Let's see
examples of writing and reading file using
fgets() functions.
Writing File : fputs() function
The fputs() function writes a line of characters
into file. It outputs string to a stream.
Syntax:
int fputs(const char *s, FILE *stream)

26
Dr.PoonGunDran,SENSE VIT, Vellore
READING FILE : FGETS()
FUNCTION
The fgets() function reads a line of characters from
file. It gets string from a stream.

Syntax:
char* fgets(char *s, int n, FILE *stream)

27
Dr.PoonGunDran,SENSE VIT, Vellore
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:
int fseek(FILE *stream, long int offset, int c)
There are 3 constants used in the fseek():
• The first parameter stream is the pointer to the file.
• The second parameter is the position of the record to be
found.
• The third parameter specifies the location where the offset
starts.

28
Dr.PoonGunDran,SENSE VIT, Vellore
29
Dr.PoonGunDran,SENSE VIT, Vellore
C rewind() function

30
Dr.PoonGunDran,SENSE VIT, Vellore
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)

As you can see, rewind() function moves the file


pointer at beginning of the file that is why "this is
simple text" is printed 2 times. If you don't call rewind()
function, "this is simple text" will be printed only once.

31
Dr.PoonGunDran,SENSE VIT, Vellore
C 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)

32
Dr.PoonGunDran,SENSE VIT, Vellore
#include<stdio.h>
#include<conio.h>
void main(){
FILE *fp;
clrscr();

fp=fopen("myfile2.txt","w");
fputs("hello c programming",fp);

fclose(fp);
getch();
}

33
Dr.PoonGunDran,SENSE VIT, Vellore
READING FILE : FGETS()
FUNCTION
The fgets() function reads a line of characters from file. It
gets string from a stream.
Syntax:
char* fgets(char *s, int n, FILE *stream)

34
Dr.PoonGunDran,SENSE VIT, Vellore
#include<stdio.h>
#include<conio.h>
void main(){
FILE *fp;
char text[300];
clrscr();

fp=fopen("myfile2.txt","r");
printf("%s",fgets(text,200,fp));

fclose(fp);
getch();
}

35
Dr.PoonGunDran,SENSE VIT, Vellore
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:
int fseek(FILE *stream, long int offset, int c)
There are 3 constants used in the fseek():
• The first parameter stream is the pointer to the file.
• The second parameter is the position of the record to be
found.
• The third parameter specifies the location where the offset
starts.

36
Dr.PoonGunDran,SENSE VIT, Vellore
37
Dr.PoonGunDran,SENSE VIT, Vellore
#include <stdio.h>
void main(){
FILE *fp;
clrscr();
fp = fopen("myfile.txt",“w+");
fputs("This is C file handling point", fp);

fseek( fp, 7, SEEK_SET);


fputs(“Hello World", fp);
fclose(fp);
}

38
Dr.PoonGunDran,SENSE VIT, Vellore
#include <stdio.h>
int main ()
{
FILE *fp;
char data[60];
fp = fopen ("test.c","w");
fputs("Fresh2refresh.com is a programming tutorial website", fp);
fgets ( data, 60, fp );
printf(Before fseek - %s", data);

// To set file pointet to 21th byte/character in the file


fseek(fp, 21, SEEK_SET);
fflush(data);
fgets ( data, 60, fp );
printf("After SEEK_SET to 21 - %s", data);

// To find backward 10 bytes from current position


fseek(fp, -10, SEEK_CUR);
fflush(data);
fgets ( data, 60, fp );
printf("After SEEK_CUR to -10 - %s", data);

// To find 7th byte before the end of file


fseek(fp, -7, SEEK_END);
fflush(data);
fgets ( data, 60, fp );
printf("After SEEK_END to -7 - %s", data);

// To set file pointer to the beginning of the file


fseek(fp, 0, SEEK_SET); // We can use rewind(fp); also

39
fclose(fp);
Dr.PoonGunDran,SENSE VIT, Vellore
return 0;
#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 ) ;
}

40
Dr.PoonGunDran,SENSE VIT, Vellore
Output:
#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 );

41
}
Dr.PoonGunDran,SENSE VIT, Vellore
C PROGRAM TO ILLUSTRATE READING OF
DATA FROM A FILE

• This C Program illustrates reading of data from a file. The program


opens a file which is present. Once the file opens successfully, it uses
libc fgetc() library call to read the content.
• Here is source code of the C program to illustrate reading of data
from a file.

42
Dr.PoonGunDran,SENSE VIT, Vellore
#include <stdio.h>
#include <stdlib.h>
void main()
{
FILE *fptr;
char filename[15],ch;
printf("Enter the filename to be opened \n");
scanf("%s", filename);
fptr = fopen(filename, "r");/*open file for reading */
if (fptr == NULL)
{ printf("Cannot open file \n");
exit(0); } File name: filex.c
ch = fgetc(fptr);
while (ch != EOF)
{ printf ("%c", ch);
ch = fgetc(fptr); }
fclose(fptr);
}

43
Dr.PoonGunDran,SENSE VIT, Vellore
C FSEEK()
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.

int fseek(FILE *stream, long int offset, int whence)

• The first parameter stream is the pointer to the file.


The second parameter is the position of the record
to be found.
• The third parameter specifies the location where the
offset starts.

44
Dr.PoonGunDran,SENSE VIT, Vellore
C FSEEK()

There are 3 constants used in the fseek() function for whence:


SEEK_SET, SEEK_CUR and SEEK_END.

45
Dr.PoonGunDran,SENSE VIT, Vellore
FILE HANDLING

46
Dr.PoonGunDran,SENSE VIT, Vellore
// OPENING A FILE

#include <stdio.h>
int main() {
FILE *fpp;

fpp = fopen("cse1002afternoon.txt","w");
fclose(fpp);
}

47
Dr.PoonGunDran,SENSE VIT, Vellore
WRITING IN TO THE FILE
#include <stdio.h>

int main() {
FILE *fp;
fp = fopen("cse1002afternoon.txt", "w");
fprintf(fp, "hello 007\n");
fclose(fp);
}

48
Dr.PoonGunDran,SENSE VIT, Vellore
READING FROM FILE
#include <stdio.h>
main(){
FILE *fp;
char buff[255];//creating char array to store data of file
fp = fopen("cse1002afternoon.txt", "r");
while(fscanf(fp, "%s", buff)!=EOF){
printf("%s ", buff );
}
fclose(fp);
}

49
Dr.PoonGunDran,SENSE VIT, Vellore
C FILE EXAMPLE: STORING EMPLOYEE
INFORMATION

• Let's see a 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.

50
Dr.PoonGunDran,SENSE VIT, Vellore
#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; }
printf("Enter the emp id:\n");
scanf("%d", &id);
fprintf(fptr, "Id= %d\n", id);
printf("Enter the emp name: \n");
scanf("%s", name);
fprintf(fptr, "Name= %s\n", name);
printf("Enter the emp salary:\n");
scanf("%f", &salary);
fprintf(fptr, "Salary= %.2f\n", salary);

51
fclose(fptr); }
Dr.PoonGunDran,SENSE VIT, Vellore
WRITING SINGLE CHARACTER INTO
FILE
#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
}

52
Dr.PoonGunDran,SENSE VIT, Vellore
READING LINE BY LINE
#include <stdio.h>
main() {
FILE *fp;
char buff[255];
fp = fopen("cse1002afternoon.txt","r");
// fscanf(fp, "%s", buff);
// printf("1 : %s\n", buff );

fgets(buff, 255, (FILE*)fp);


printf("1: %s\n", buff );

fgets(buff, 255, (FILE*)fp);


printf("2: %s\n", buff );

fgets(buff, 255, (FILE*)fp);

53
printf("3: %s\n", buff );
Dr.PoonGunDran,SENSE VIT, Vellore
fclose(fp); }
Writing Single character and
reading Single Character in to
the file using putc and getc.

54
Dr.PoonGunDran,SENSE VIT, Vellore
FPUTC AND FGETC

#include <stdio.h> // fputc and fgetc


#include<conio.h>
void main(){
FILE *fp;
char c;
fp = fopen("file123.txt","w");//opening file
fputc('r',fp);//writing single character into file
fclose(fp);
fp = fopen("file123.txt","r");
while((c=fgetc(fp))!=EOF) {
printf("%c",c); }
fclose(fp);//closing file
}

55
Dr.PoonGunDran,SENSE VIT, Vellore
READ CHAR BY CHAR
#include<stdio.h>
#include<conio.h>
void main(){
FILE *fp;
char c;
fp=fopen("cse1001morning.txt","r");
while((c=fgetc(fp))!=EOF){
printf("%c",c);
}
fclose(fp);
getch();

56
}Dr.PoonGunDran,SENSE VIT, Vellore
PUTS AND GETS.
Writing string and reading tring in to
the file using puts and gets.

57
Dr.PoonGunDran,SENSE VIT, Vellore
#include<stdio.h>// fputs and gets
#include<conio.h>
void main(){
FILE *fp;
char text[300];
fp=fopen("myfile2.txt","w");
fputs("hello c programming",fp);
fclose(fp);
fp=fopen("myfile2.txt","r");
printf("%s",fgets(text,300,fp));
fclose(fp);
}

58
Dr.PoonGunDran,SENSE VIT, Vellore
FSEEK
#include <stdio.h>
void main(){
FILE *fp;

fp = fopen("myfile124.txt","w+");
fputs("This is C Programming", fp);

fseek( fp, 8, SEEK_SET );


fputs("Poongundran Welcome ", fp);
fclose(fp);
}

59
Dr.PoonGunDran,SENSE VIT, Vellore
REWIND
#include<stdio.h>
#include<conio.h>
void main(){
FILE *fp;
char c;
fp=fopen("cse1001morning.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);

60
}
Dr.PoonGunDran,SENSE VIT, Vellore
FTELL
#include <stdio.h>
#include <conio.h>
void main (){
FILE *fp;
int length;
fp = fopen("cse1001morning.txt", "r");
fseek(fp, 0, SEEK_END);
length = ftell(fp);
fclose(fp);
printf("Size of file: %d bytes", length);
}

61
Dr.PoonGunDran, SENSE VIT, Vellore

You might also like