0% found this document useful (0 votes)
22 views

File Handling in C

The document discusses file handling in C. It explains what files are, the different types of files, and how to perform basic operations like opening, reading, writing and closing files using functions like fopen(), fclose(), fprintf(), fscanf() etc. It also discusses using file pointers and different file access modes.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views

File Handling in C

The document discusses file handling in C. It explains what files are, the different types of files, and how to perform basic operations like opening, reading, writing and closing files using functions like fopen(), fclose(), fprintf(), fscanf() etc. It also discusses using file pointers and different file access modes.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 29

File Handling in C

Harapriya Mohanta
Why needed?
• Data stored in variables, arrays are temporary, lost when the program
terminates.
• All the programs so far discussed performed some calculations and show the
result to the console or terminal screen. These outcomes are not stored
anywhere, i.e., the ouput is available when the program is running and once
the program is terminated, its output or result gets vanished.
console screen

---------- output
-
program

• To permanently store data created in a program, it is required to save in file.

©Harapriya Mohanta
What is a file?

• Just like a container that can store information. HARD DRIVE


-
• It can be defined as collection of bytes or ---
stream of bytes that hold /store the data & --- ---
content that are stored in hard disk(secondary --- ---
storage). --
files

©Harapriya Mohanta
Two kinds of Files: (Data Stream)
• Text file or text stream: stream of characters(bytes).
- contains ASCII codes only.
- human readable form and can be created and read using text editor.
• Binary files or Bianary stream: stream of unprocessed byte.
- can contain non-ASCII charaters.
 also image, audio,video, etc.
- not in human readable form and they can be created and read only by specific programs
written for them.
- can’t be read using text editor.

©Harapriya Mohanta
How file is stored?
• stored as sequence of bytes, logically contiguous (may not be
physically contiguous on disk)
• The last byte of a file contains the end of file marker.

Adress index
3200 0 image → 𝑑𝑖𝑓𝑓𝑒𝑟𝑒𝑛𝑡 𝑟𝑒𝑝𝑟𝑒𝑠𝑒𝑛𝑡𝑎𝑡𝑖𝑜𝑛
3201 1 text → 𝑑𝑖𝑓𝑓𝑒𝑟𝑒𝑛𝑡 𝑟𝑒𝑝𝑟𝑒𝑠𝑒𝑛𝑡𝑎𝑡𝑖𝑜𝑛
:
:
:
EOF : macro defined in
:
stdio.h, value is -1
:
but to check the end of
:
file in case of bianry, the
:
file size value need to be n-
4000 End of File Marker
checked 1

©Harapriya Mohanta
read
input stream buffer
stdin write
output stream buffer

stdout
read
Program-- write
--------- Error stderr

©Harapriya Mohanta
file handling in c: How to work with the files?
• file handling is a way of dealing with the data of file stored in the hard drive from a program.
• By using file handling, the c program can read the data from the file or write the data into the
file located in the hard disk.

Operation on file:
• creating a new file
• writing on new files
• overwriting on existing files
• reading from files
• closing the files

©Harapriya Mohanta
step 1: To do different operations on file, first thing that we need is to create or to declare a pointer
to a file
FILE *fp;
FILE - a structure designed to be used for working on files and it is defined in stdio.h
step2: opening or giving access to a file
How it is going to be done? -

fp = fopen(“filename”, “type of operation”)

• if successfully created, return specify what way are you expecting


pointer to a file your program interact with a given
• if failed or on error, returns NULL. file, whether it is going to be used
for writing, reading or appending

©Harapriya Mohanta
• fclose():
It is a predefined function, declared in stdio.h .
We can close the file after saving the data.
It requires one argument of type FILE* and returns an int value
Syntax: int fclose(FILE* stream).

©Harapriya Mohanta
Types of operation/modes:
• “w” - creates a file for writing and writes over all previous contents(deletes the
data so be careful!)
• “r” - opens a file for reading
• “a” - opens a file for appending means writing at the end of the file
• “w+” - (write+read)- if file is exist, then previous data erased. if file doesn’t exist,
then a new file is created
• “r+” - (read+write)- file must exist and we canread and write also but my
previous data in the file will not be erased.
• “a+” - (append+read)- if file exists then new data is appended and if file doesnot
exist, a new file is created.
• Binary mode: To open a fin bianry mode, we can append ‘b’ to the mode
• wb, rb, ab, wb+,rb+,ab+

©Harapriya Mohanta
Functions used for file I/O:

• Character I/O : fgetc(), fputc()


• String I/O: fgets(), fputs()
• Formatted I/O: fscanf(), fprintf()
• Record I/O (structure variable) : fread(), fwrite()

©Harapriya Mohanta
Character I/O : fgetc(), fputc()
• fgetc():
It is a predefined unformatted function that is declared in stdio.h.
By using this function we can read a character from a given file and increments the
file pointer position.
It returns an int value .i.e., ASCII value of a character
Syntax: int fgetc(FILE *fp);
• fputc():
It is a predefined unformatted function that is declared in stdio.h.
By using this function we can write a character to a specified file and increments
the file pointer position
It returns an int value .i.e., ASCII value of a character
Syntax: int fputc(<character>, FILE *fp);

©Harapriya Mohanta
Ex: #include <stdio.h>
int main() { //step1-create a pointer to file
FILE *fp;
// step-2 open the file in write mode to write into the file
fp = fopen("file1.txt","w");
//step3 make sure the opening is succesful or not
if(fp==NULL)
{
printf("file is not opened\n");
exit(0);
}
// step4- work with file

printf("file is successfully opened in write mode\n");


fputc(‘h’, fp); // taking a character and puting it inside where fp is pointing to
fputc(‘i’, fp);
//step5- close the file
fclose(fp);

return 0;
}
©Harapriya Mohanta
String I/O: fgets(), fputs()
• fgets():
It reads string from file.
fgets(str, Number of character, File pointer)
• fputs():
It write string to file.
fputs(str, File pointer)
It doesnot add \n (newline) by default. You will have to specify it explicitly.

©Harapriya Mohanta
Example of fputs() and fgets():
#include<stdio.h>
int main()
{
char name[40];
FILE *fp = fopen(“file1.txt”, “w”);
fputs(“Hey!”,fp);
fputs(“I am Nilisha.”,fp);
fputs(“hey!\n”,fp);
fclose(fp);
fp = fopen(“file1.txt”,”r”);
fgets(name,10,fp);
fclose(fp);
printf(“%s”,name);
return 0;
}
©Harapriya Mohanta
Formatted I/O : fscanf(), fprintf()
• fprintf(): It is used to write data (of different variables) to the file.
• Syntax: fprintf(file_ptr, “format specifier”, variables);
• ex: fprintf(fp,”%d %f %c”, a,b,c);

• fscanf(): It is used to read multiple values from the file and stored them in
suitable variables.
• Syntax: fscanf(file_ptr, “format specifier”, &variable);

©Harapriya Mohanta
EX:
#include<stdio.h>
int main()
{
char name[20];
int age;
float cgpa;
FILE *fp;

printf(“enter your details(name,age,cgpa):”);


gets(name);
scanf(“%d %f”, &age,&cgpa);

fp= fopen(“file2.txt”,”w”);
fprintf(fp,”%s %d %f”,name,age,cgpa);
fclose(fp);
fp= fopen(“file2.txt”,”r”);
fscanf(fp,”%s %d %f”,name,&age,&cgpa);
fclose(fp);

printf(“Name: %s\nage: %d\nCGPA: %f”, name,age,cgpa);


return 0;
} ©Harapriya Mohanta
int main() { else{
FILE *fp; printf("file is successfully opened in read mode\n");
char str[10]; printf("enter name:");
int num; gets(str);
float f; printf("\nenter a two number(integer, float):");
char str2[50]; scanf("%d %f",&num,&f);
fp = fopen("file3.txt","w"); fprintf(fp,"Name:%s \nNum:%d \nfloat number:%f",str,num,f);
int i; fclose(fp);
if(fp==NULL) fp = fopen("file2.txt","r");
{ fscanf(fp,"%s %d %f",str,&num,&f);
printf("not created"); fclose(fp);
exit(1); printf("%s %d %f",str,num,f);
}
}
return 0;
}

©Harapriya Mohanta
Record I/O (structure variable): fread(), fwrite()
• These functions are used to read/write data from/to a file. This is useful when
we want to deal with user-defined variables such as structure.
• fwrite(): write data to the file
syntax: fwrite(ptr to memory,size,no of items, fp)
• fread(): read data from file
syntax: fread(ptr,size,no of items,fp)

©Harapriya Mohanta
struct student
{
char name[10];
int roll;
}s1;
int main() {
int a;
FILE *fp;
printf("enter name:");
scanf("%s",s1.name);
printf("\nenter roll:");
scanf("%d",&s1.roll);
fp =fopen("text2.txt","w");
fwrite(&s1,sizeof(s1),1,fp);
fclose(fp);
fp =fopen("text2.txt","r");
fread(&s1,sizeof(s1),1,fp);
printf("student data:\n");
printf("Student name:%s\nRoll NO:%d",s1.name,s1.roll);
fclose(fp);
return 0;
}
©Harapriya Mohanta
Binary FILES: Reading / Writing struct objects(variables)
• Disadvantage of Text file:
• Text file is a file where the data of any type is first converted into text and then stored.
• coversion have to take place while transferring data between memory and file.
• ex: the number 345678 will be first converted into individual characters and stored in the file
as ‘3’, ‘4’, ’5’, ’6’, ’7,’ ’8’. When we read the data from the file then text type is again converted
into number type.
• More memory space required: Storing the number as individual characters take more
memory than storing the number as its binary equivalent. It takes only 4 bytes to store
345678 in the main memory but takes 6 bytes in text files.
• Low Performance: It takes more time in I/O operations while in binary files takes less time as
no conversions have to take place while transfering of data between memory and file.

345678 RAM
345678
00000000 00000101 01000110 01001110
6 bytes
file
©Harapriya Mohanta
Binary FILES:

• We can save the memory and improve performance by directly writing the
binary data on to the file.
• It cant be opened with any other applications.
• No additional code is required to perform write /read/append operations on
the binary files. The only difference is in the mode that is used to open the
file.
• Ex: FILE *fp = fopen(“filename/path”, “wb”); - opens binary file in write mode

©Harapriya Mohanta
Random Access to files:
• In general we access the data from a file character by character or record by record from
the beginning of the file to the end of file called sequential access. If the size of file is so
small then takes reasonable time to get the required record but takes time if a file has
1000’s of records.

• for example, a file has 10000 records and has to get 9999th record then we have to all the
way go through 9999 records to get the required record, results take a lot of time.

• We can overcome this by directly accessing a record from the required position. It can be
done in two steps that are, sending the file active pointer to the required position using
fseek() and reading the record using fread() as we learned in the previous session.
• In C, three functions can help us to access the files in random access fashion
✓ ftell()
✓ rewind()
✓ fseek()

©Harapriya Mohanta
ftell():
- It returns the current position of the file pointer in the file.
- The value is calculated from the beginning of the file.
- Syntax: ftell(fp);

rewind():
- This function used to reset the file pointer position to the beginning of the file.
- Syntax: rewind(fp);

fseek() function:
• It is the function used to send the file pointer to the specified position from the specified
position.
• Syntax: int fseek(fp,long displacement,int origin)
• return 0 when successfully reached and non-zero if failed.
©Harapriya Mohanta
These are the three possible values of the position:

• SEEK_SET 0 -- beginning of the file


• SEEK_CURRENT 1 -- CURRENT POSITION ON FILE
• SEEK_END 2 -- END OF THE FILE

fseek(fp,0,0) - moves file pointer to the beginning(same as rewind) of


the file.
fseek(fp,2,0)- moves 2bytes from beginning
fseek(fp,n,0)- moves n bytes in forward direction from the beginning
fseek(fp,n,1)- from the cuurent position
fseek(fp,-n,1)- backward direction from cuurent position
fseek(fp,-n,2)- backward direction from EOF

©Harapriya Mohanta
int main() {
int a; rewind(fp);
int ch; //fseek(fp,0,2)
FILE *fp; printf("\nfp postion:%d",fp);
fp= fopen("new.txt","r"); /*
a = ftell(fp); fseek(fp,-8,2);
printf("fp postion:%d",a);//0
printf("\nfp postion:%d",fp); while((ch=fgetc(fp))!=EOF)
//a = fseek(fp,8,1); {
//printf("fp postion:%d",a); printf("%c",ch);
} */
while((ch=fgetc(fp))!=EOF) fclose(fp);
{ return 0;
printf("%c",ch); }
}
a = ftell(fp);
printf("\nfp postion:%d",a);

©Harapriya Mohanta
Ex2:

struct student
{
char name[10];
//char roll[10];
int roll;
};
int main() {
struct student s1;
int n,i,student;
FILE *fp;
fp =fopen("text2.txt","wb");

printf("enter the no of students:");


scanf("%d",&n);

©Harapriya Mohanta
for(i=1;i<=n;i++)
{
printf("enter name:");
scanf("%s",s1.name);
printf("enter roll:");
scanf("%d",&s1.roll);

fwrite(&s1,sizeof(s1),1,fp);
}

fclose(fp);

fp =fopen("text2.txt","rb");

©Harapriya Mohanta
while(1)
{
printf("\nenter the student no:");
scanf("%d",&student);
if(student<1 || student>n)
{
printf("search failure:");
}
else{
fseek(fp,(student-1)*sizeof(s1),0);
fread(&s1,sizeof(s1),1,fp);
printf("student data:\n");
printf("Student name:%s\nRoll no:%d",s1.name,s1.roll);
}

}
fclose(fp);
return 0;
}

©Harapriya Mohanta

You might also like