Working With Files

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

Working With Files

Why files are needed?


• When a program is terminated, the entire data is lost. Storing in a file will
preserve your data even if the program terminates.
• If you have to enter a large number of data, it will take a lot of time to enter
them all.
However, if you have a file containing all the data, you can easily access the
contents of the file using a few commands in C.
• You can easily move your data from one computer to another without any
changes.
What is File Handling in C?
A file is nothing but a source of storing information permanently in the form of a
sequence of bytes on a disk. The contents of a file are not volatile like the C
compiler memory. The various operations available like creating a file, opening a
file, reading a file or manipulating data inside a file is referred to as file handling.
File Operation Mode
Whenever you open or create a file, you have to specify what you are going to do
with the file. A file in 'C' programming can be created or opened for
reading/writing purposes. A mode is used to specify whether you want to open a
file for any of the below-given purposes. Following are the different types of
modes in 'C' programming which can be used while working with a file.
File Mode Description
r Open a file for reading. If a file is in reading mode, then no
data is deleted if a file is already present on a system.
w Open a file for writing. If a file is in writing mode, then a
new file is created if a file doesn't exist at all. If a file is
already present on a system, then all the data inside the file
is truncated, and it is opened for writing purposes.

a Open a file in append mode. If a file is in append mode,


then the file is opened. The content within the file doesn't
change.
r+ open for reading and writing from beginning

w+ open for reading and writing, overwriting a file

a+ open for reading and writing, appending to file


BASIC FILE OPERATIONS IN C PROGRAMMING:
There are 4 basic operations that can be performed on any files in C programming
language. They are,
• Opening/Creating a file
• Closing a file
• Reading a file
• Writing in a file

File operation Declaration & Description


Declaration: FILE *fopen (const char *filename, const char
*mode)
fopen() function is used to open a file to perform operations such
as reading, writing etc. In a C program, we declare a file pointer
and use fopen() as below. fopen() function creates a new file if the
mentioned file name does not exist.
fopen() – To FILE *fp;
open a file fp=fopen (“filename”, ”‘mode”);
Where,
fp – file pointer to the data type “FILE”.
filename – the actual file name with full path of the file.
mode – refers to the operation that will be performed on the file.
Example: r, w, a, r+, w+ and a+. Please refer below the description
for these mode of operations.
Declaration: int fclose(FILE *fp);
fclose() function closes the file that is being pointed by
fclose() – To close a file file pointer fp. In a C program, we close a file as below.
fclose (fp);

Declaration: char *fgets(char *string, int n, FILE *fp)


fgets function is used to read a file line by line. In a C
program, we use fgets function as below.
fgets() – To read a file fgets (buffer, size, fp);
where,
buffer – buffer to put the data in.
size – size of the buffer
fp – file pointer

Declaration:
int fprintf(FILE *fp, const char *format, …);fprintf()
fprintf() – To write into a function writes string into a file pointed by fp. In a C
file program, we write string into a file as below.
fprintf (fp, “some data”); or
fprintf (fp, “text %d”, variable_name);
File Processing Techniques
Depending up on the method of accessing the data stored ,there are two types of
files.
• Sequential file
• Random access file
1.Sequential File: In this type of files data is kept in sequential order if we want to
read the last record of the file,we need to read all records before that record so it
takes more time.
2.Random access Files: In this type of files data can be read and modified randomly
.If we want to read the last record we can read it directly.It takes less time when
compared to sequential file.
rewind()
The C library function void rewind(FILE *stream) sets the file position to the
beginning of the file of the given stream.
Declaration
• Following is the declaration for rewind() function.
• void rewind(FILE *stream)
Parameters
• stream − This is the pointer to a FILE object that identifies the stream.
fseek()
The C library function int fseek(FILE *stream, long int offset, int whence) sets the
file position of the stream to the given offset.
Declaration
• Following is the declaration for fseek() function.
• int fseek(FILE *stream, long int offset, int whence)
Parameters
• stream − This is the pointer to a FILE object that identifies the stream.
• offset − This is the number of bytes to offset from whence.
• whence − This is the position from where offset is added. It is specified by one
of the following constants −

Sr.No. Constant & Description


1 SEEK_SET
Beginning of file
2 SEEK_CUR
Current position of the file pointer
3 SEEK_END
End of file

#include <stdio.h>
int main () {
FILE *fp;
fp = fopen("file.txt","w+");
fputs("This is tutorialspoint.com", fp);
fseek( fp, 7, SEEK_SET );
fputs(" C Programming Language", fp);
fclose(fp);
return(0);
}
ftell() in C
• In C language, ftell() returns the current file position of the specified stream
with respect to the starting of the file. This function is used to get the total size
of file after moving the file pointer at the end of the file. It returns the current
position in long type and file can have more than 32767 bytes of data.
Here is the syntax of ftell() in C language,
long int ftell(FILE *stream)
Here is the parameter used in ftell(),
• stream − This is the pointer to a FILE object that identifies the stream.
#include <stdio.h>
#include<conio.h>
void main () {
FILE *f;
int len;
f = fopen("one.txt", "r");
if(f == NULL) {
perror(“Error opening file”);
return(-1);
}
opening read write and appending on from data file in c
The character I/O
fgetc()
• fgetc() is used to obtain input from a file single character at a time. This function
returns the ASCII code of the character read by the function. It returns the
character present at position indicated by file pointer. After reading the
character, the file pointer is advanced to next character. If pointer is at end of file
or if an error occurs EOF file is returned by this function.
fputc()
• fputc() is used to write a single character at a time to a given file. It writes the
given character at the position denoted by the file pointer and then advances the
file pointer.
This function returns the character that is written in case of successful write
operation else in case of error EOF is returned.
#include<stdio.h>
#include<conio.h>
void main() {
FILE *f;
char s;
clrscr();
f=fopen("new.txt","r");
while((s=fgetc(f))!=EOF) {
printf("%c",s);
}
fclose(f);
getch(); }
#include
<stdio.h>
void main() {
FILE *f;
f = fopen("new.txt", "w");
fputc('a',f);
fclose(f);
}
The program will modify the “new.txt” file. It will not display any output to the
screen but it will modify the file directly. You can check the modified file.
The string I/O
The fputs() function writes a line of characters into file. It outputs string to a
stream.
int fputs(const char *s, FILE *stream)
The fgets() function reads a line of characters from file. It gets string from a stream.
char* fgets(char *s, int n, FILE *stream)
#include<stdio.h>
#include<conio.h>
void main(){
FILE *fp;
clrscr();
fp=fopen("myfile2.txt","w");
fputs("hello c programming",fp);
fclose(fp);
getch();
}
#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();
}
The formatted I/O
The fprintf() function is used to write set of characters into file. It sends formatted
output to a stream.
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);
}
#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
}
Record Block I/O
• It is useful to store the block of data into the file rather than individual
elements.Each block has some fixed size,it may be of strcture or of an array.It is
possible that a data file has one or more structures or arrays,So it is easy to read
the entire block from file or write the entire block to the file.There are two
useful functions for this purpose
1. fwrite():
• This function is used for writing an entire block to a given file.
Write a program to read an employee details and write them into the file at a
time using fwrite().
#include<stdio.h>
#include<conio.h>
void main() {
struct emp {
int eno;
char ename[20];
float sal;
}e;
FILE *fp;
fp=fopen("emp.dat", "wb");
clrscr();
printf("Enter employee number");
scanf("&d",&e.eno);
printf("Enter employee name");
fflush(stdin);
scanf("%s",e.ename);
printf("Enter employee salary");
scanf("%f",&e.sal);
fwrite(&e,sizeof(e),1,fp);
printf("One record stored successfully");
getch();
}
2. fread():
• This function is used to read an entire block from a given file.
• Syntax: fread ( ptr , size , nst , fptr);
Where ptr is a pointer which points to the array which receives structure.
Size is the size of the structure
nst is the number of the structure
fptr is a filepointer.
Write a program to read an employee details at a time from a file using fread()
which are written above using fwrite()and display them on the output screen.
#include<stdio.h>
#include<conio.h>
void main() {
struct emp
{
int eno;
char ename[20];
float sal;
}e;
FILE *fp;
fp=fopen("emp.dat", "rb");
clrscr();
if(fp==NULL)
printf("File cannot be opened");
else
fread(&e,sizeof(e),1,fp);
printf("\nEmployee number is %d",e.eno);
printf("\nEmployee name is %s",e.ename);
printf("\nEmployee salary is %f",e.sal);
printf("One record read successfully");
getch();
}
fprintf ()
• This function is same as the printf() function but it writes the data into the file,
so it has one more parameter that is the file pointer.
Syntax: fprintf(fptr, "controlcharacter",variable-names);
Where fptr is a file pointer
Control character specifies the type of data to be printed into file.
Variable-names hold the data to be printed into the file.
fscanf ()
• This function is same as the scanf() function but this reads the data from the file,
so this has one more parameter that is the file pointer.
Syntax: fscanf(fptr, "control character", &variable-names);
Where fptr is a file pointer
Control character specifies the type of data to be read from the file.
Address of Variable names are those that hold the data read from the file.
Write a program to read details of an employee and print them in a file using
fprintf() and read the same from the file using fscanf() and display on the output
screen.
#include<stdio.h>
#include<conio.h>
void main() {
FILE *fp; int eno;
char ename[20];
float sal;
clrscr();
fp=fopen("emp.dat", "w+");
printf("Enter employee number");
scanf("&d",eno);
printf("Enter employee name");
fflush(stdin);
scanf("%s",ename);
printf("Enter employee salary");
scanf("%f",sal);
fprintf(fp, "%d %s %f\n",eno,ename,sal);
printf("Details of an employee are printed into file");
rewind(fp);
fscanf(fp,"%d %s %f",&eno,ename,&esal);
printf("Details of employee are\n");
printf("\n %d %s %f", eno,ename, sal);
fclose(fp);
getch();
}
Binary Mode operations
• Binary mode deals with data records and these records can be in the form of a
single byte or several bytes. Most often structured objects are stored in binary
mode and are stored sequentially.
Binary Mode fopen flags
#1 Binary Read (rb) SYNTAX:
Opens a file in binary read mode fp=fopen("binary.dat","rb");

#2 Binary write (wb) SYNTAX:


Opens a file in binary write mode. fp=fopen("binary.dat","wb");

#3 Binary append (ab) SYNTAX:


Opens a file in binary append mode fp=fopen("binary.dat","ab");
i.e. to add at the end of file.
#4 Binary read+write (r+b) SYNTAX:
Opens preexisting file in read and fp=fopen("binary.dat","r+b");
write mode.
#5 Binary write+read (w+b) SYNTAX:
Open file for binary reading and writing fp=fopen("binary.dat","w+b");
also creates a new file if not exists.

#6 Binary append+write (a+b) SYNTAX:


Opens file in append mode i.e. data can fp=fopen("binary.dat","a+b");
be written at the end of file.

You might also like