0% found this document useful (0 votes)
8 views10 pages

FILE Handling

Uploaded by

nareshm3225
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)
8 views10 pages

FILE Handling

Uploaded by

nareshm3225
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/ 10

A file is a container in computer storage devices used for storing data.

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, and provide the least security and takes
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

In C, you can perform four major operations on files, either text or binary:

1. Creating a new file


2. Opening an existing file

3. Closing a file

4. Reading from and writing information to a file

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("newprogram.txt","w");

fopen("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.

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: 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("program.txt","w");

if(fptr == NULL)
{
printf("Error!");
exit(1);
}

printf("Enter num: ");


scanf("%d",&num);

fprintf(fptr,"%d",num);
fclose(fptr);

return 0;
}
This program takes a number from the user and stores in the file program.txt.

After you compile and run this program, you can see a text file program.txt created in C drive of your
computer. When you open the file, you can see the integer you entered.

Example 2: Read from a text file

#include <stdio.h>
#include <stdlib.h>

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

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


printf("Error! opening file");
// Program exits if the file pointer returns NULL.
exit(1);
}

fscanf(fptr,"%d", &num);

printf("Value of n=%d", num);


fclose(fptr);

return 0;
}
This program reads the integer present in the program.txt file and prints it onto the screen.

If you successfully created the file from Example 1, running this program will get you the integer you
entered.

Other functions like fgetchar(), fputc() etc. can be used in a similar way.

Example:

#include <stdio.h>

int main(){

FILE * file, *f1;

char c;

file = fopen("abc.txt", "r");

f1 = fopen("xyz.txt", "w");

while((c=getc(file))!=EOF)

fputc(c,f1);

printf("%c", c);

fclose(file);

fclose(f1);

return 0;

This program is copying content of file abc.txt to file xyz.txt character by character and also is
printing same to terminal.

getc(filepointer) returns a character which is stored in variable c and that is written in the file xyz.txt
through pointer f1 function used here is fputc(c,f1).
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.

Syntax:

fwrite(addressData, sizeData, numbersData, pointerToFile);

Example 3: Write to a binary file using fwrite()

#include <stdio.h>
#include <stdlib.h>

struct threeNum
{
int n1, n2, n3;
};

int main()
{
int n;
struct threeNum num;
FILE *fptr;

if ((fptr = fopen("program.bin","wb")) == NULL){


printf("Error! opening file");

// Program exits if the file pointer returns NULL.


exit(1);
}

for(n = 1; n < 5; ++n)


{
num.n1 = n;
num.n2 = 5*n;
num.n3 = 5*n + 1;
fwrite(&num, sizeof(struct threeNum), 1, fptr);
}
fclose(fptr);

return 0;
}
In this program, we create a new file program.bin. We declare a structure threeNum with three
numbers - n1, n2 and n3, and define it in the main function as num. Now, inside the for loop, we
store the value into the file using fwrite(). The first parameter takes the address of num and the
second parameter takes the size of the structure threeNum. Since we're only inserting one instance
of num, the third parameter is 1. And, the last parameter *fptr points to the file we're storing the
data. Finally, we close the file.

Reading from a binary file

Function fread() also take 4 arguments similar to the fwrite() function as above.

Syntax: fread(addressData, sizeData, numbersData, pointerToFile);

Example 4: 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("program.bin","rb")) == NULL){


printf("Error! opening file");

// Program exits if the file pointer returns NULL.


exit(1);
}

for(n = 1; n < 5; ++n)


{
fread(&num, sizeof(struct threeNum), 1, fptr);
printf("n1: %d\tn2: %d\tn3: %d\n", num.n1, num.n2, num.n3);
}
fclose(fptr);

return 0;
}
In this program, you read the same file program.bin and loop through the records one by one.

In simple terms, you read one threeNum record of threeNum size from the file pointed by *fptr into
the structure num.

You'll get the same records you inserted in Example 3.

Getting data using fseek()

fseek() is used to move file pointer associated with a given file to a specific position.
If you have many records inside a file and need to access a record at a specific position, you need to
loop through all the records before it to get the record.

This will waste a lot of memory and operation time. An easier way to get to the required data can be
achieved using fseek().

As the name suggests, fseek() seeks the cursor to the given record in the file.

Syntax of fseek()

Syntax:

int fseek(FILE *pointer, long int offset, int position)

pointer: pointer to a FILE object that identifies the stream.

offset: number of bytes to offset from position

position: position from where offset is added.

returns:

zero if successful, or else it returns a non-zero value

position defines the point with respect to which the file pointer needs to be moved. It has three
values:
SEEK_END : It denotes end of the file.
SEEK_SET : It denotes starting of the file.
SEEK_CUR : It denotes file pointer’s current position.

Example 5: fseek()

#include <stdio.h>
#include <stdlib.h>

struct threeNum
{
int n1, n2, n3;
};

int main()
{
int n;
struct threeNum num;
FILE *fptr;

if ((fptr = fopen("C:\\program.bin","rb")) == NULL){


printf("Error! opening file");

// Program exits if the file pointer returns NULL.


exit(1);
}
// Moves the cursor to the end of the file
fseek(fptr, -sizeof(struct threeNum), SEEK_END);

for(n = 1; n < 5; ++n)


{
fread(&num, sizeof(struct threeNum), 1, fptr);
printf("n1: %d\tn2: %d\tn3: %d\n", num.n1, num.n2, num.n3);
fseek(fptr, -2*sizeof(struct threeNum), SEEK_CUR);
}
fclose(fptr);

return 0;
}

C Programming – C Union – Syntax and Examples

Union is an user defined datatype in C programming language. It is a collection of variables of


different datatypes in the same memory location. We can define a union with many members, but
at a given point of time only one member can contain a value. Unions can be very handy when you
need to talk to peripherals through some memory mapped registers.

Need for Union in C programming

C unions are used to save memory. To better understand an union, think of it as a chunk of
memory that is used to store variables of different types. When we want to assign a new value to
a field, then the existing data is replaced with new data. C unions allow data members which are
mutually exclusive to share the same memory. This is quite important when memory is valuable,
such as in embedded systems. Unions are mostly used in embedded programming where direct
access to the memory is needed.

Difference between structure and union

The main difference between structure and a union is that Structs allocate enough space to store
all of the fields in the struct. The first one is stored at the beginning of the struct, the second is
stored after that, and so on. Unions only allocate enough space to store the largest field listed, and
all fields are stored at the same space .

Syntax for Declaring a C union

Syntax for declaring a union is same as that of declaring a structure except the keyword struct.

union union_name {

datatype field_name;

datatype field_name;

// more variables

};
Size of the union is the the size of its largest field because sufficient number of bytes must
be reserved to store the largest sized field. To access the fields of a union, use dot(.)
operator i.e., the variable name followed by dot operator followed by field name.
Initializing unions:

The difference between structure and union when their initialization is given below.

#include <stdio.h>

struct test1 {

int x, y;

};

union test {

int x, y;

};

int main() {

struct test1 t1={1,2};

union test t;

t.x = 3; // t.y also gets value 3

printf ("after fixing x value the coordinates of t will be %d %d\n\n",t.x, t.y);

t.y = 4; // t.x is also updated to 4

printf ("After fixing y value the coordinates of t will be %d %d\n\n", t.x, t.y);

printf("The coordinates of t1 are %d %d",t1.x,t1.y);

return 0;

Output: after fixing x value the coordinates of t will be 3 3

After fixing y value the coordinates of t will be 4 4

The coordinates of t1 are 1 2

The fields of a union cannot be initialized all at once. For a structure variable the output is fine but
for the union variable the answer does not seem to be correct because union can hold single value
for a member at a time i.e., the data is over-written in the memory. Obviously the use case we have
chosen is not suited for union but only struct. This example is only to demonstrate the behavior of
union and structure.

Dynamic Memory ALLocation

You might also like