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

Unit-IV_Files

Uploaded by

jainaishwarya084
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views

Unit-IV_Files

Uploaded by

jainaishwarya084
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 33

Unit-IV

Files

Ms. Priyanka Parmar


Computer Application
Medicaps University, Indore
File
 File is a collection of data that stored on secondary
memory like hard disk of a computer.

 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.

Priyanka Parmar Medicaps University,Indore


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.

Priyanka Parmar Medicaps University,Indore


File Handling

Priyanka Parmar Medicaps University,Indore


File Operations

 The following operations can be performed on the


file:-
 A)Creation of New File.
 B)Opening an existing file.
 C)Reading from file
 D)Writing to file
 E)Moving specific location in a file.
 F)Closing a file.

Priyanka Parmar Medicaps University,Indore


Types of Files in C

 A file can be classified into two types based on the way the file
stores the data. They are as follows:
• Text Files
• Binary Files

Priyanka Parmar Medicaps University,Indore


Text Files
 The text files are the most basic/simplest types of files that a
user can create in a C program. We create the text files using an
extension .txt with the help of a simple text editor. In general,
we can use notepads for the creation of .txt files. These files
store info internally in ASCII character format, but when we
open these files, the content/text opens in a human-readable
form.
 Text files are, thus, very easy to access as well as use. But
there’s one major disadvantage; it lacks security. Since a .txt file
can be accessed easily, information isn’t very secure in it.
Added to this, text files consume a very large space in storage.
 To solve these problems, we have a different type of file in C
programs, known as binary files.
Priyanka Parmar Medicaps University,Indore
Text Files

A text file contains data in the form of ASCII characters


and is generally used to store a stream of characters.

 Each line in a text file ends with a new line character


(‘\n’).
 It can be read or written by any text editor.
 They are generally stored with .txt file extension.
 Text files can also be used to store the source code.

Priyanka Parmar Medicaps University,Indore


Binary Files

 The binary files store info and data in the binary format of 0’s
and 1’s (the binary number system). Thus, the files occupy
comparatively lesser space in the storage. In simpler words, the
binary files store data and info the same way a computer holds
the info in its memory. Thus, it can be accessed very easily as
compared to a text file.
 The binary files are created with the extension .bin in a
program, and it overcomes the drawback of the text files in a
program since humans can’t read it; only machines can. Thus,
the information becomes much more secure. Thus, binary files
are safest in terms of storing data files in a C program.

Priyanka Parmar Medicaps University,Indore


Binary Files
 A binary file contains data in binary form (i.e. 0’s and
1’s) instead of ASCII characters. They contain data
that is stored in a similar manner to how it is stored in
the main memory.
 The binary files can be created only from within a
program and their contents can only be read by a
program.
 More secure as they are not easily readable.
 They are generally stored with .bin file extension.

Priyanka Parmar Medicaps University,Indore


Types of Files

Priyanka Parmar Medicaps University,Indore


fprintf() function
The fprintf() function is almost identical to the
printf() function. The only difference is that the
fprintf() function writes data into the given file.
The purpose of the fprintf() function is to write
formatted data to a file.
In the fprintf() function, the file pointer points to
the file where the formatted output will be
written
Priyanka Parmar Medicaps University,Indore
Syntax:
 int fprintf(FILE *stream, const char *format [, argum
ent, ...])
 In both function above-given syntax, input passes by
two parameters. Those two parameters are as follows:
 Stream: A stream is a pointer to the file that indicates
the file object which recognizes the file stream.
 Format: It is the parameter that tells about how to
format the data according to the user's requirements or
to make the data easy to read.

Priyanka Parmar Medicaps University,Indore


Example of fprintf() function

#include <stdio.h>
void main()
{
FILE *fptr;
fptr = fopen(“abc.txt", "w"); //opening file
fprintf(fptr, "Hello, Welcome to Medicaps.\n"); //writing data into file
fclose(fptr); //closing file
}

Priyanka Parmar Medicaps University,Indore


fscanf() function

 The fscanf() function reads the stream in the form of byte,


interprets the input according to the format, and stores the
format into their argument for the output. It reads from a file
that also contains a pointer, i.e., file pointer, so it reads a
specific area or part of the file instead of the whole stream.
 fscanf() function of the C programming language reads a
specific part of the file instead of reading the whole stream. For
this process, the fscanf() function uses a file pointer. This
function works on two parameters: streams and formats. This
stream is the file's pointer, and the format contains a list of
placeholders used to read the specific type of data.

Priyanka Parmar Medicaps University,Indore


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

Stream: A stream is a pointer to the file that indicates the file


object which recognizes the file stream.
Format: It is the parameter that tells about how to format the
data according to the user's requirements or to make the data
easy to read.
 It reads a word from the file and returns EOF at the end of
file.

Priyanka Parmar Medicaps University,Indore


Program
 #include <stdio.h>
 void main()
{
 FILE *fptr;
 char a[200]; //creating char array to store data of file
 fptr = fopen(“abc.txt", "r");
 while(fscanf(fptr, "%s", a)!=EOF)
 {
 printf("%s ", a);
 }
 fclose(fptr);
}
Priyanka Parmar Medicaps University,Indore
Creating a new file

 We use the fopen() function to create a new file and


open an existing file in our storage.
 The syntax of fopen()-
fopen("filename","mode")
 When declaring a file in C, the pointer of the file type
(FILE) is used to point the file. fopen() will give the
file address to the file pointer which is going to
create/open.
 Let's create a new file with the name file2.txt.

Priyanka Parmar Medicaps University,Indore


Program to create file
 #include <stdio.h>
 int main(){
 FILE * file;
 file = fopen("file2.txt","w");
}
 A new file will be created in the folder where your
code is saved. You can also specify the path to your
file's creation. file = fopen ("C://file2.txt", "w");
 We use write mode because it will create a new file if
the file is not present.
Priyanka Parmar Medicaps University,Indore
Opening an Existing File

 We use fopen() with the required opening modes to open an


existing file, as discussed. We have already created a file using
write mode. In the following code, use r mode. That is, open the
file in read mode.
 #include <stdio.h>
 int main()
{
 FILE * file;
 file = fopen("file2.txt","r");
}

Priyanka Parmar Medicaps University,Indore


Writing Data to a File

 Let's write in the file that we created in the previous


example. So to do that, I'll be using fprintf() to write a
text in the file with the name file2.txt.
 #include <stdio.h>
 int main(){
 FILE *file;
 file = fopen("file2.txt", "w");
 fprintf(file, "Hello! Welcome to Medicaps.\n");
}

Priyanka Parmar Medicaps University,Indore


Reading Data From an Existing File

 To read data from an existing file, we will use “r”


mode in file opening. To read the file character by
character, we use getc(). And to read line by line, we
use fgets().

Priyanka Parmar Medicaps University,Indore


 #include <stdio.h>
 #include <stdlib.h>
.
 int main() {
 FILE * fp;
 char s;
 fp = fopen("file2.txt", "r");
 if (fp == NULL) {
 printf("\nCAN NOT OPEN FILE");
 exit(1);
 }
 do {s = getc(fp); // Read file character by character.
 printf("%c", s);
 }
 while (s != EOF);
 fclose(fp); Priyanka Parmar Medicaps University,Indore
Moving Data to a Specific Location on the File

 To put the file pointer to a specific place, we use fseek(). With the
help of it, we can write data at whatever location we want in the
file.
 Syntax -
 fseek(FILE stream, long int offset, int whence)
 file stream - pointer to the file. As in the example file, the pointer to
the file object "myfile.txt".
 offset - This is the number of bytes that must be offset/skipped from
whence.
 Hence take three values.
 SEEK_SET - sets the pointer at the beginning of the
file. SEEK_CUR - sets the pointer at the current position of the
file SEEK_END - sets the pointer at the end of the file.
Priyanka Parmar Medicaps University,Indore
Program
 #include <stdio.h>
 int main(){
 FILE *file;
 file = fopen("myfile.txt","w+");
 fputs("Welcome to Medicaps” , file);
 fseek( file, 10, SEEK_SET );
 fputs(" Computer Apllications !", file);
 printf("%s",file);
 fclose(file);
}

Priyanka Parmar Medicaps University,Indore


 Initially,
the output will be Welcome to Medicaps But
we had reset the right pointer at the 10th position from
the beginning, i.e., W, and using the help of fputs(), the
statement is overwritten. The final output is Welcome
to Computer Applications.

Priyanka Parmar Medicaps University,Indore


Closing the File
 To close a file that is already open, we will use fclose(). As
we have already discussed the syntax of it, we will directly
head over to the example.
 #include <stdio.h>
 int main(){
 FILE *file;
 file = fopen("file2.txt", "w");
 fprintf(file, "Hello! Welcome to Medicaps.\n");
 fclose(file);
}
 In this example, the file is the pointer associated with the
file(file2.txt) which is to be closed. After closing the file, the
file pointer lost the reference
Priyanka Parmar
of the file and started pointing to
Medicaps University,Indore
NULL.
Functions for reading

 fscanf():-Use formatted string and variable arguments


list to take input from a file.
 fgets():-Input the whole line from the file.
 fgetc():-Reads a single character from the file.
 fgetw():-Reads a number from a file.
 fread():-Reads the specified bytes of data from a
binary file.

Priyanka Parmar Medicaps University,Indore


Functions for writing
 fprintf():-Similar to printf(), this function use
formatted string and varible arguments list to print
output to the file.
 fputs():-Prints the whole line in the file and a newline
at the end.
 fputc():-Prints a single character into the file.
 fputw():-Prints a number to the file.
 fwrite():-This functions write the specified amount of
bytes to the binary file.

Priyanka Parmar Medicaps University,Indore


File Modes
 “r”-Searches file. If the file is opened successfully fopen( )
loads it into memory and sets up a pointer which points to the
first character in it. If the file cannot be opened, fopen( ) returns
NULL. Operations possible – reading from the file.
 "w" Searches file. If the file exists, its contents are overwritten.
If the file doesn’t exist, a new file is created. Returns NULL, if
unable to open file. Operations possible – writing to the file.
 "a" Searches file. If the file is opened successfully fopen( )
loads it into memory and sets up a pointer that points to the last
character in it. If the file doesn’t exist, a new file is created.
Returns NULL, if unable to open file. Operations possible -
adding new contents at the end of file

Priyanka Parmar Medicaps University,Indore


 "r+" Searches file. If is opened successfully fopen( ) loads it
into memory and sets up a pointer which points to the first
character in it. Returns NULL, if unable to open the file.
Operations possible - reading existing contents, writing new
contents, modifying existing contents of the file.

 "w+" Searches file. If the file exists, its contents are


overwritten.If the file doesn’t exist, a new file is created.
Returns NULL, if unable to open file.Operations possible -
writing new contents, reading them back and modifying
existing contents of the file.

Priyanka Parmar Medicaps University,Indore


 "a+" Searches file. If the file is opened successfully fopen( )
loads it into memory and sets up a pointer which points to the
first character in it. If the file doesn’t exist, a new file is created.
Returns NULL, if unable to open file.Operations possible -
reading existing contents, appending new contents to end of
file. Cannot modify existing contents.
 “rb”-Open for reading in binary mode.If file does not exist
fopen() returns NULL.
 “wb”- Open for writing in binary mode. If the file exists, its
contents are overwritten. If the file does not exist, it will be
created.

Priyanka Parmar Medicaps University,Indore


 “ab”- Open for append in binary mode.Data is added
to the end of the file. If the file does not exist, it will
be created.
 “rb+” Open for both reading and writing in binary
mode. If the file does not exist, fopen() returns NULL.
 “wb+” Open for both reading and writing in binary
mode.If the file exists, its contents are overwritten.If
the file does not exist, it will be created.
 “ab+” Open for both reading and appending in binary
mode. If the file does not exist, it will be created.

Priyanka Parmar Medicaps University,Indore

You might also like