Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Files in C

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

UNIT V

FILES in C
C File Handling
• A file is a container in computer storage devices used for storing data.

• File handing in C is the process in which we create, open, read, write,


and close operations on a file.

• C language provides different functions such as fopen(), fwrite(),


fread(), fseek(), fprintf(), etc. to perform input, output, and many
different C file operations in our program.
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.
Types of Files
• When dealing with files, there are two types of files you should know
about:
1.Text files
2.Binary files
1. Text files
• Text files are the normal .txt files. You can easily create text files
using any simple text editors such as Notepad.

• When you open those files, you'll see all the contents within the file as
plain text. You can easily edit or delete the contents.

• They take minimum effort to maintain, are easily readable, provide the
least security, and take bigger storage space.
2. Binary files
• Binary files are mostly the .bin files in your computer.
• Instead of storing data in plain text, they store it in the binary form (0's
and 1's).
• They can hold a higher amount of data, are not readable easily, and
provides better security than text files.
File Operations
• C file operations refer to the different possible operations that we can
perform on a file in C such as:
1.Creating 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()
• The highlighted text mentions the C function used to perform the file
operations.
Working with files
• When working with files, you need to declare a pointer of type file.
This declaration is needed for communication between the file and the
program.

FILE *fptr;
Opening a file - for creation and edit
Opening a file is performed using the fopen() function defined in
the stdio.h header file.

The syntax for opening a file in standard I/O is:

ptr = fopen("fileopen","mode");

For example, fopen("E:\\cprogram\\newprogram.txt","w");


fopen("E:\\cprogram\\oldprogram.bin","rb");
•Let's suppose the file newprogram.txt doesn't exist in the location E:\cprogram. The first
function creates a new file named newprogram.txt and opens it for writing as per the
mode 'w’.

The writing mode allows you to create and edit (overwrite) the contents of the file.

•Now let's suppose the second binary file oldprogram.bin exists in the location E:\cprogram.
The second function opens the existing file for reading in binary mode 'rb’.

The reading mode only allows you to read the file, you cannot write into the file.
Opening Modes in Standard I/O
Mode Meaning of Mode During Inexistence of file
r Open for reading. If the file does not exist, fopen() returns NULL.

rb Open for reading in binary mode. If the file does not exist, fopen() returns NULL.

If the file exists, its contents are overwritten.


w Open for writing.
If the file does not exist, it will be created.

If the file exists, its contents are overwritten.


wb Open for writing in binary mode.
If the file does not exist, it will be created.

Open for append.


a If the file does not exist, it will be created.
Data is added to the end of the file.
Open for append in binary mode.
ab If the file does not exist, it will be created.
Data is added to the end of the file.

r+ Open for both reading and writing. If the file does not exist, fopen() returns NULL.

Open for both reading and writing in


rb+ If the file does not exist, fopen() returns NULL.
binary mode.

If the file exists, its contents are overwritten.


w+ Open for both reading and writing.
If the file does not exist, it will be created.

Open for both reading and writing in If the file exists, its contents are overwritten.
wb+
binary mode. If the file does not exist, it will be created.

a+ Open for both reading and appending. If the file does not exist, it will be created.

Open for both reading and appending in


ab+ If the file does not exist, it will be created.
binary mode.
Closing a File
• The file (both text and binary) should be closed after reading/writing.

Closing a file is performed using the fclose() function.

fclose(fptr);

Here, fptr is a file pointer associated with the file to be closed.


Reading and writing to a text file

For reading and writing to a text file, we use the


functions fprintf() and fscanf().

They are just the file versions of printf() and scanf(). The
only difference is that fprintf() and fscanf() expects a
pointer to the structure FILE.
Example 1: Write to a text file
#include <stdio.h>
#include <stdlib.h>

int main()
{
int num;
FILE *fptr;

// use appropriate location if you are using MacOS or Linux


fptr = fopen("D:\\program.txt","w");

if(fptr == NULL)
{
Example 2: Read from a text file
#include <stdio.h>
#include <stdlib.h>

int main()
{
int num;
FILE *fptr;

if ((fptr = fopen("D:\\program.txt","r")) == NULL){


printf("Error! opening file");

// Program exits if the file pointer returns NULL.


exit(1);
Function Description
Use formatted string and variable arguments list to take input from a
fscanf()
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.


Function Description
Similar to printf(), this function use formatted string and varible
fprintf()
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.

This functions write the specified amount of bytes to the binary


fwrite()
file.
Reading and writing to a binary file

Functions fread() and fwrite() are used for reading from and
writing to a file on the disk respectively in case of binary
files.
Writing to a binary file
To write into a binary file, you need to use the fwrite() function. The
functions take four arguments:

1.address of data to be written in the disk


2.size of data to be written in the disk
3.number of such type of data
4.pointer to the file where you want to write.
fwrite(addressData, sizeData, numbersData, pointerToFile);

fwrite(const void *ptr, size_t size, size_t nmemb, FILE *file_pointer);


Example 3: Write to a binary file using
fwrite()
// C program to write to a Binary file using fwrite()
#include <stdio.h>
#include <stdlib.h>
struct threeNum {
int n1, n2, n3;
};
int main()
{
int n;
// Structure variable declared here.
Reading from Binary File
• The fread() function can be used to read data from a binary file in C.
The data is read from the file in the same form as it is stored i.e. binary
form.

• Syntax of fread()
size_t fread(void *ptr, size_t size, size_t nmemb, FILE *file_pointer);
Parameters:
• ptr: pointer to the block of memory to read.
• size: the size of each element to read(in bytes).
• nmemb: number of elements.
• file_pointer: FILE pointer to the input file stream.

Return Value:
• Number of objects written.
Program to Read from a binary file using
fread()
// C Program to Read from a binary file using fread()
#include <stdio.h>
#include <stdlib.h>
struct threeNum {
int n1, n2, n3;
};
int main()
{
int n;
struct threeNum num;
FILE* fptr;
if ((fptr = fopen("D:\\program.bin", "rb")) == NULL) {
printf("Error! opening file");
fseek() in C
• If we have multiple records inside a file and need to access a particular
record that is at a specific position, so we need to loop through all the
records before it to get the record.

• Doing this will waste a lot of memory and operational time.

• To reduce memory consumption and operational time we can use fseek()


which provides an easier way to get to the required data.

• fseek() function in C seeks the cursor to the given record in the file.
Syntax for fseek()
int fseek(FILE *ptr, long int offset, int pos);
// C Program to demonstrate the use of fseek() in C
#include <stdio.h>

int main()
{
FILE* fp;
fp = fopen("D:\\program.txt", "r");

// Moving pointer to end


fseek(fp, 0, SEEK_END);

// Printing position of pointer


printf("%ld", ftell(fp));

return 0;
}
rewind() in C
• The rewind() function is used to bring the file pointer to the beginning
of the file. It can be used in place of fseek() when you want the file
pointer at the start.

• Syntax of rewind()

rewind (file_pointer);
Example
// C program to illustrate the use of rewind
#include <stdio.h>

int main()
{
FILE* fptr;
fptr = fopen("D:\\program.txt", "w+");
fprintf(fptr, "good afternoon students\n");

// using rewind()
rewind(fptr);

// reading from file


char buf[50];
fscanf(fptr, "%[^\n]s", buf);

printf("%s", buf);
Difference between fseek() and rewind() in C

fseek rewind
fseek is used to move the file pointer to a specific rewind is used to move the file pointer to the
position. beginning of the file stream.

Syntax: Syntax:
int fseek(FILE *stream, long offset, int origin); void rewind(FILE *stream);

It returns 0 if successful, and a non-zero value if an


It does not return any value.
error occurs.

The stream error indicator is not cleared. The stream error indicator is cleared.

Example: fseek(file, 10, SEEK_SET);


Example: rewind(file);
It moves the file pointer 10 bytes from the beginning
It moves the file pointer to the beginning of the file.
of the file.

You might also like