Monday, 28 March 2016

File Handling In C

File Handling in C

File Handling in c language is used to open, read, write, search or close file. It is used for permanent storage.

Advantage of File

It will contain the data even after program exit. Normally we use variable or array to store data, but data is lost after program exit. Variables and arrays are non-permanent storage medium whereas file is permanent storage medium.

Functions for file handling

There are many functions in C library to open, read, write, search and close file. A list of file functions are given below:
No.FunctionDescription
1fopen()opens new or existing file
2fprintf()write data into file
3fscanf()reads data from file
4fputc()writes a character into file
5fgetc()reads a character from file
6fclose()closes the file
7fseek()sets the file pointer to given position
8fputw()writes an integer to file
9fgetw()reads an integer from file
10ftell()returns current position
11rewind()sets the file pointer to the beginning of the file

Opening File

The fopen() function is used to open a file. The syntax of fopen() function is given below:
  1. FILE *fopen( const char * filename, const char * mode );  
You can use one of the following modes in the fopen() function.
ModeDescription
ropens a text file in read mode
wopens a text file in write mode
aopens a text file in append mode
r+opens a text file in read and write mode
w+opens a text file in read and write mode
a+opens a text file in read and write mode
rbopens a binary file in read mode
wbopens a binary file in write mode
abopens a binary file in append mode
rb+opens a binary file in read and write mode
wb+opens a binary file in read and write mode
ab+opens a binary file in read and write mode

Closing File

The fclose() function is used to close a file. The syntax of fclose() function is given below:
  1. int fclose( FILE *fp );  

Writing File : fprintf() function

The fprintf() function is used to write set of characters into file.
  1. #include <stdio.h>  
  2. main(){  
  3.    FILE *fp;  
  4.    fp = fopen("file.txt""w");//opening file  
  5.    fprintf(fp, "Hello file by fprintf...\n");//writing data into file  
  6.    fclose(fp);//closing file  
  7. }  

Reading File : fscanf() function

The fscanf() function is used to read set of characters from file.
  1. #include <stdio.h>  
  2. main(){  
  3.    FILE *fp;  
  4.    char buff[255];//creating char array to store data of file  
  5.    fp = fopen("file.txt""r");  
  6.    fscanf(fp, "%s", buff);//reading data of file and writing into char array  
  7.    printf("Data is : %s\n", buff );//printing data of char array  
  8.    fclose(fp);  
  9. }  
Output:
Data is : Hello file by fprintf...

C File Example: Storing employee information

Let's see a file handling example to store employee information as entered by user from console. We are going to store id, name and salary of the employee.
  1. #include <stdio.h>  
  2. void main()  
  3. {  
  4.     FILE *fptr;  
  5.     int id;  
  6.     char name[30];  
  7.     float salary;  
  8.     fptr = fopen("emp.txt""w+");/*  open for writing */  
  9.     if (fptr == NULL)  
  10.     {  
  11.         printf("File does not exists \n");  
  12.         return;  
  13.     }  
  14.     printf("Enter the id\n");  
  15.     scanf("%d", &id);  
  16.     fprintf(fptr, "Id= %d\n", id);  
  17.     printf("Enter the name \n");  
  18.     scanf("%s", name);  
  19.     fprintf(fptr, "Name= %s\n", name);  
  20.     printf("Enter the salary\n");  
  21.     scanf("%f", &salary);  
  22.     fprintf(fptr, "Salary= %.2f\n", salary);  
  23.     fclose(fptr);  
  24. }  
Output:
Enter the id 
1
Enter the name 
sonoo
Enter the salary
120000 
Now open file from current directory. For windows operating system, go to TC\bin directory, you will see emp.txt file. It will have following information.
emp.txt
Id= 1
Name= sonoo
Salary= 120000 


Structures n C

Structure in C

Structure in c language is a user defined datatype that allows you to hold different type of elements.
Each element of a structure is called a member.
It works like a template in C++ and class in Java. You can have different type of elements in it.
It is widely used to store student information, employee information, product information, book information etc.

Defining structure

The struct keyword is used to define structure. Let's see the syntax to define structure in c.
  1. struct structure_name   
  2. {  
  3.     data_type member1;  
  4.     data_type member2;  
  5.     .  
  6.     .  
  7.     data_type memeberN;  
  8. };  
Let's see the example to define structure for employee in c.
  1. struct employee  
  2. {   int id;  
  3.     char name[50];  
  4.     float salary;  
  5. };  
Here, struct is the keyword, employee is the tag name of structure; idname and salary are the members or fields of the structure. Let's understand it by the diagram given below:
c structure

Declaring structure variable

We can declare variable for the structure, so that we can access the member of structure easily. There are two ways to declare structure variable:
  1. By struct keyword within main() function
  2. By declaring variable at the time of defining structure.
1st way:
Let's see the example to declare structure variable by struct keyword. It should be declared within the main function.
  1. struct employee  
  2. {   int id;  
  3.     char name[50];  
  4.     float salary;  
  5. };  
Now write given code inside the main() function.
  1. struct employee e1, e2;  
2nd way:
Let's see another way to declare variable at the time of defining structure.
  1. struct employee  
  2. {   int id;  
  3.     char name[50];  
  4.     float salary;  
  5. }e1,e2;  

Which approach is good

But if no. of variable are not fixed, use 1st approach. It provides you flexibility to declare the structure variable many times.
If no. of variables are fixed, use 2nd approach. It saves your code to declare variable in main() fuction.

Accessing members of structure

There are two ways to access structure members:
  1. By . (member or dot operator)
  2. By -> (structure pointer operator)
Let's see the code to access the id member of p1 variable by . (member) operator.
  1. p1.id  

C Structure example

Let's see a simple example of structure in C language.
  1. #include <stdio.h>  
  2. #include <string.h>  
  3. struct employee    
  4. {   int id;    
  5.     char name[50];    
  6. }e1;  //declaring e1 variable for structure  
  7. int main( )  
  8. {  
  9.    //store first employee information  
  10.    e1.id=101;  
  11.    strcpy(e1.name, "Sonoo Jaiswal");//copying string into char array  
  12.    //printing first employee information  
  13.    printf( "employee 1 id : %d\n", e1.id);  
  14.    printf( "employee 1 name : %s\n", e1.name);  
  15.    return 0;  
  16. }  
Output:
employee 1 id : 101
employee 1 name : Sonoo Jaiswal
Let's see another example of structure in C language to store many employees information.
  1. #include <stdio.h>  
  2. #include <string.h>  
  3. struct employee    
  4. {   int id;    
  5.     char name[50];    
  6.     float salary;    
  7. }e1,e2;  //declaring e1 and e2 variables for structure  
  8. int main( )  
  9. {  
  10.    //store first employee information  
  11.    e1.id=101;  
  12.    strcpy(e1.name, "Sonoo Jaiswal");//copying string into char array  
  13.    e1.salary=56000;  
  14.   
  15.   //store second employee information  
  16.    e2.id=102;  
  17.    strcpy(e2.name, "James Bond");  
  18.    e2.salary=126000;  
  19.    
  20.    //printing first employee information  
  21.    printf( "employee 1 id : %d\n", e1.id);  
  22.    printf( "employee 1 name : %s\n", e1.name);  
  23.    printf( "employee 1 salary : %f\n", e1.salary);  
  24.   
  25.    //printing second employee information  
  26.    printf( "employee 2 id : %d\n", e2.id);  
  27.    printf( "employee 2 name : %s\n", e2.name);  
  28.    printf( "employee 2 salary : %f\n", e2.salary);  
  29.   
  30.    return 0;  
  31. }  
Output:
employee 1 id : 101
employee 1 name : Sonoo Jaiswal
employee 1 salary : 56000.000000
employee 2 id : 102
employee 2 name : James Bond
employee 2 salary : 126000.000000

Nested Structure in C

Nested structure in c language can have another structure as a member. There are two ways to define nested structure in c language:
  1. By separate structure
  2. By Embedded structure

1) Separate structure

We can create 2 structures, but dependent structure should be used inside the main structure as a member. Let's see the code of nested structure.
  1. struct Date  
  2. {  
  3.    int dd;  
  4.    int mm;  
  5.    int yyyy;   
  6. };  
  7. struct Employee  
  8. {     
  9.    int id;  
  10.    char name[20];  
  11.    struct Date doj;  
  12. }emp1;  
As you can see, doj (date of joining) is the variable of type Date. Here doj is used as a member in Employee structure. In this way, we can use Date structure in many structures.

2) Embedded structure

We can define structure within the structure also. It requires less code than previous way. But it can't be used in many structures.
  1. struct Employee  
  2. {     
  3.    int id;  
  4.    char name[20];  
  5.    struct Date  
  6.     {  
  7.       int dd;  
  8.       int mm;  
  9.       int yyyy;   
  10.     }doj;  
  11. }emp1;  

Accessing Nested Structure

We can access the member of nested structure by Outer_Structure.Nested_Structure.member as given below:
  1. e1.doj.dd  
  2. e1.doj.mm  
  3. e1.doj.yyyy  

C Nested Structure example

Let's see a simple example of nested structure in C language.
  1. #include <stdio.h>  
  2. #include <string.h>  
  3. struct Employee  
  4. {     
  5.    int id;  
  6.    char name[20];  
  7.    struct Date  
  8.     {  
  9.       int dd;  
  10.       int mm;  
  11.       int yyyy;   
  12.     }doj;  
  13. }e1;  
  14. int main( )  
  15. {  
  16.    //storing employee information  
  17.    e1.id=101;  
  18.    strcpy(e1.name, "Sonoo Jaiswal");//copying string into char array  
  19.    e1.doj.dd=10;  
  20.    e1.doj.mm=11;  
  21.    e1.doj.yyyy=2014;  
  22.   
  23.    //printing first employee information  
  24.    printf( "employee id : %d\n", e1.id);  
  25.    printf( "employee name : %s\n", e1.name);  
  26.    printf( "employee date of joining (dd/mm/yyyy) : %d/%d/%d\n", e1.doj.dd,e1.doj.mm,e1.doj.yyyy);  
  27.    return 0;  
  28. }  
Output:
employee id : 101
employee name : Sonoo Jaiswal
employee date of joining (dd/mm/yyyy) : 10/11/2014

C Union

Like structure, Union in c language is a user defined datatype that is used to hold different type of elements.
But it doesn't occupy sum of all members size. It occupies the memory of largest member only. It shares memory of largest member.
difference between structure and union

Advantage of union over structure

It occupies less memory because it occupies the memory of largest member only.

Disadvantage of union over structure

It can store data in one member only.

Defining union

The union keyword is used to define union. Let's see the syntax to define union in c.
  1. union union_name   
  2. {  
  3.     data_type member1;  
  4.     data_type member2;  
  5.     .  
  6.     .  
  7.     data_type memeberN;  
  8. };  
Let's see the example to define union for employee in c.
  1. union employee  
  2. {   int id;  
  3.     char name[50];  
  4.     float salary;  
  5. };  

C Union example

Let's see a simple example of union in C language.
  1. #include <stdio.h>  
  2. #include <string.h>  
  3. union employee    
  4. {   int id;    
  5.     char name[50];    
  6. }e1;  //declaring e1 variable for union  
  7. int main( )  
  8. {  
  9.    //store first employee information  
  10.    e1.id=101;  
  11.    strcpy(e1.name, "Sonoo Jaiswal");//copying string into char array  
  12.    //printing first employee information  
  13.    printf( "employee 1 id : %d\n", e1.id);  
  14.    printf( "employee 1 name : %s\n", e1.name);  
  15.    return 0;  
  16. }  
Output:
employee 1 id : 1869508435
employee 1 name : Sonoo Jaiswal
As you can see, id gets garbage value because name has large memory size. So only name will have actual value.