File Handling In C

A file represents a sequence of bytes on the disk where a group of related data is stored. File is created for permanent storage of data. It is a ready made structure.

In C language, we use a structure pointer of file type to declare a file.

File functions :

fopen() :

C fopen is a C library function used to open an existing file or create a new file.
Syntax :

FILE *fopen( const char * filePath, const char * mode );

filePath: The first argument is a pointer to a string containing the name of the file to be opened.

mode: The second argument is an access mode.

Mode Description
r Opens an existing text file.
w Opens a text file for writing if the file doesn’t exist then a new file is created.
a Opens a text file for appending(writing at the end of existing file) and create the file if it does not exist.
r+ Opens a text file for reading and writing.
w+ Open for reading and writing and create the file if it does not exist. If the file exists then make it blank.
a+ Open for reading and appending and create the file if it does not exist. The reading will start from the beginning, but writing can only be appended.

Lets See an Example :

#include <stdio.h>

int main()
{
FILE *fp;
fp = fopen(“fileName.txt”,”w”);
return 0;
}

The above example will create a file called fileName.txt.
The w means that the file is being opened for writing, and if the file does not exist then the new file will be created
fclose() :

The fclose() function is used to close a file. The file must be closed after performing all the operations on it. The syntax of fclose() function is given below:
Syntax :

fclose(fptr); //fptr is the file pointer associated with 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, fprint and fscanf expects a pointer to the structure FILE.
Lets take ans example :

#include <stdio.h>
#include <stdlib.h>
int main()
{
int num;
FILE *fptr;
fptr = fopen(“C:\\program.txt”,”w”);
if(fptr == NULL)
{
printf(“Error!”);
exit(1);
}
printf(“Enter num: “);
scanf(“%d”,&num);
fprintf(fptr,”%d”,num);
fclose(fptr);
return 0;
}

Lets take an example fscanf() :

#include <stdio.h>
#include <stdlib.h>
int main()
{
int num;
FILE *fptr;
if ((fptr = fopen(“C:\\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 similar way.
Search data using fseek() :

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() :

fseek(FILE * stream, long int offset, int whence)

The first parameter stream is the pointer to the file. The second parameter is the position of the record to be found, and the third parameter specifies the location where the offset starts.
SEEK_SET:
Starts the offset from the beginning of the file.
SEEK_END:
Starts the offset from the end of the file.
SEEK_CUR:
Starts the offset from the current location of the cursor in the file.
Example of fseek()

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;
}

This program will start reading the records from the file program.bin in the reverse order (last to first) and prints it.

Lets do some programming exercises :

1.Write a program in C to write multiple lines in a text file.

2. Write a program in C to count a number of words and characters in a file.

3. Write a program in C to replace a specific line with another text in a file

4. Write a program in C to copy a file in another name

typedef in C

typedef is a keyword used in C language to assign alternative names to existing datatypes. Its mostly used with user defined datatypes, when names of the datatypes become slightly complicated to use in programs. Following is the general syntax for using typedef,
Lets take an simple example :

                            typedef unsigned long ulong;
                    

The above statement define a term ulong for an unsigned long datatype. Now this ulong identifier can be used to define unsigned long type variables.

Application of typedef :


typedef can be used to give a name to user defined data type as well. Lets see its use with structures.

                                        
                    typedef struct
                    {
                        type member1;
                        type member2;
                        type member3;
                    } type_name;
                


Here type_name represents the stucture definition associated with it. Now this type_name can be used to declare a variable of this stucture type.

We can define Structure using typedef :

 

                    #include <stdio.h>
                    #include <string.h>
                    
                    typedef struct employee
                    {
                        char name[50];
                        int salary;
                    }emp;
                    
                    void main( )
                    {
                        emp e1;
                        printf("\nEnter Employee record:\n");
                        printf("\nEmployee name:\t");
                        scanf("%s", e1.name);
                        printf("\nEnter Employee salary: \t");
                        scanf("%d", &e1.salary);
                        printf("\nstudent name is %s", e1.name);
                        printf("\nroll is %d", e1.salary);
                    }
                

Use typedef and Pointers


typedef can be implemented for providing a pseudo name to pointer variables as well. In this below-mentioned code snippet, you have to use the typedef, as it is advantageous for declaring pointers.

                        int* a;
                


The binding of pointer (*) is done to the right here. With this kind of statement declaration, you are in fact declaring an as a pointer of type int (integer).

Program of structure in C with the use of typedef:

 

                    #include <stdio.h>
                    #include<string.h>

                    typedef struct professor
                    {
                        char p_name[50];
                        int p_sal;
                    } prof;

                    void main(void)
                    {
                        prof pf;
                        printf("\n Enter Professor details: \n  \n");
                        printf("\n Enter Professor name:\t");
                        scanf("% s", pf.p_name);
                        printf("\n Enter professor salary: \t");
                        scanf("% d", &pf.p_sal);
                        printf("\n Input done ! ");
                    }