new UNIT-V
new UNIT-V
Structure - Nested structures – Pointer and Structures – Array of structures – Self-referential structures – Dynamic
memory allocation - Singly linked list – typedef – Union - Storage classes and Visibility. Files – Types of file
processing: Sequential access, Random access – Sequential access file - Random access file - Command line
arguments
5.1 INTRODUCTION
● As we know that, Array is a collection of elements of same type, but many times we have to store the
elements of different data types.
● The structure is a convenient way of grouping several pieces of related information together.
● Structure is a collection of different variables under single name.
};
5.4 STRUCTURE DECLARATION
The structure can be declared with the keyword struct following the name and opening brace with data
elements of different type, and then closing brace with semicolon. Structure can be declared as follows:
Syntax:
main()
{
struct date today;
}
//Way
. 3 : Declaring Multiple Structure Variables
struct date
{
int day;
char month[20];
int year;
}yesterday,today,tomorrow;
}s;
void main()
{
int total;
clrscr();
printf("Enter student details:\n");
printf("Enter student name:");
scanf(" %s”,s.name);
printf("Enter student rollno:");
scanf(" %d ",&s.rollno);
printf("Enter subject mark:");
scanf(" %d%d %d %d %d %d",&s.maths,&s.eng,&s.phy,&s.chem,&s.pc);
total=s.maths+s.eng+s.phy+s.chem+s.pc ;
s.avg=total/5;
printf("\nAverage of %s,RollNo:%d is %d and %0.2f", s.name,s.rollno,s.avg);
getch();
}
Output:
Enter student details:
Enter student name, rollno, mark1, mark2, mark3: Banu 6 99 98 97 98 97
Average of Banu,RollNo.6 is 98.00
struct Bookinfo
{
char Name[20];
int Pages;
float Price;
}Book[100];
Explanation :
1. Here Book structure is used to Store the information of one Book.
2. In case if we need to store the Information of 100 books then Array of Structure is used.
3. Book[0] stores the Information of 1st Book ,B[1] stores the information of 2nd Book and So on
We can store the information of 100 books.
Book[3] is shown Below
for(i=0;i<n;i++)
printf("\n%s\t%d\t%d\t%d\t%d\t%d\t%f\t%c",s[i].name,s[i].rollno,s[i].m1,s[i].m2,s[i].m3,s[i].tot,s[i].avg,
s[i].grade);
getch();
}
OUTPUT
Enter number of students:
3 Enter Student 1 details
Enter name:abi
Enter Rollno:1
Enter 3 subject marks:90
89
98
Enter Student 2 details
Enter name:meena
Enter Rollno:6
Enter 3 subject marks:78
90
89
Enter Student 3 details
Enter name:priya
Enter Rollno:6
Enter 3 subject marks:56
78
76
STUDENTS MARK SHEET
#include <stdio.h>
struct employee
{
char name[10];
int basic, da, hra, ta, others;
int pf,it;
int net_salary,gross_salary,detection;
}e[10];
//main program
void main()
{
int i,n;
struct employee *ptr[10];
clrscr();
printf("enter the number of employee");
scanf("%d",&n);
for(i=0;i<n;i++)
{
ptr[i]=&e[i]; printf("enter
the name");
scanf("%s",ptr[i]->name);
printf("Enter Basic Salary (RS): ");
scanf("%d",&ptr[i]->basic);
ptr[i]->hra=(ptr[i]->basic*15)/100; ptr[i]->ta=(ptr[i]->basic*20)/100;
ptr[i]->others=(ptr[i]->basic*10)/100;
//calculate DA 12% of Basic Salary
ptr[i]->da = (ptr[i]->basic*30)/100;
//calculate PF 14% of Basic salary
ptr[i]->pf = (ptr[i]->basic*2)/100;
//calculate IT, 15% of Basic salary
ptr[i]->it = (ptr[i]->basic*2)/100;
//calculate net salary
ptr[i]->gross_salary = ptr[i]->basic + ptr[i]->da + ptr[i]->hra + ptr[i]->ta + ptr[i]->others;
ptr[i]->deduction=ptr[i]->pf+ptr[i]->it;
ptr[i]->net_salary=ptr[i]->gross_salary-ptr[i]-> deduction;
}
//printing Net salary
for(i=0;i<n;i++)
{
printf("\n Name is %s",ptr[i]->name);
printf("\t Net Salary is:RS %d\n",ptr[i]->net_salary);
}
getch(); }
EXAMPLE PROGRAM FOR STUDENT DATABASE PROGRAM
#include<stdio.h>
#include<string.h>
struct student
{
char name[20];
int roll_no, i;
int marks;
}a[10];
void main()
{
int i,n;
struct student *arr_student[10];
clrscr();
printf("enter the number of Student");
scanf("%d",&n);
printf("enter the Student Details one by one");
for(i=0;i<n;i++)
{
arr_student[i]= &a[i];
printf("\nEnter details of student" );
printf("Enter name: ");
scanf("%s", arr_student[i]->name);
printf("Enter roll no: ");
scanf("%d", &arr_student[i]->roll_no);
printf("Enter marks: ");
scanf("%d", &arr_student[i]->marks);
}
for(i=0;i<n;i++)
{
printf("\n");
printf("Name\tRoll no\tMarks\n");
printf("%s\t%d\t%d\n",arr_student[i]->name, arr_student[i]->roll_no, arr_student[i]->marks);
getch();
}
OUTPUT
#include<stdio.h>
struct student
{
char name[50];
int rollno;
int mark;
};
void printstr(char[],int,int);
int main()
{
struct student s1={“xyz”,7,92};
printstr(s1);
return 0;
}
void printstr(struct student s)
{
printf(“Name=%s”,s.name);
printf(“Rollno=%d”,s.rollno);
printf(“Mark=%d”,s.mark);
}
POINTER TO STRUCTURE AS ARGUMENTS:
#include<stdio.h>
struct student
{
char name[50];
int rollno;
int mark;
};
void printstr(struct student *);
int main()
{
struct student s1={“xyz”,7,92};
struct student *sp;
sp=&s1;
printstr(sp);
return 0;
}
void printstr(struct student *p)
{
printf(“Name=%s”,p->name); //p->name ==(*p).name
printf(“Rollno=%d”,p->.rollno);
printf(“Mark=%d”,p>mark);
}
RETURNING STRUCTURE VARIABLE FROM FUNCTION:
#include<stdio.h>
struct student createstr(char[],int,int);
int main()
{
struct student s;
s=createstr(“xyz”,7,92);
printf(“Name=%s”,s.name);
printf(“Rollno=%d”,s.rollno);
printf(“Mark=%d”,s.mark);
}
struct student createstr(char name[],int rollno,int mark)
{
struct student s1;
strcpy(s1.name,name);
s1.rollno=rollno;
s1.mark=mark;
return s1;
}
RETURNING POINTER FROM A STRUCTURE:
#include<stdio.h>
struct student *createstr(char[],int,int);
int main()
{
struct student *p;
p=createstr(“xyz”,7,92);
printf(“Name=%s”,p->name); //p->name ==(*p).name
printf(“Rollno=%d”,p->.rollno);
printf(“Mark=%d”,p>mark);
}
struct student *createstr(char name[],int rollno,int mark)
{
static struct student s1; //without static it will print nothing
strcpy(s1.name,name);
s1.rollno=rollno;
s1.mark=mark;
return &s1;
}
struct address
{
char st[20];
char city[20];
long int pin;
}add;
struct employee
{
int empid;
char name[20];
struct dob dt;
char pan[10];
long int phone;
struct address add;
char dept[10];
int exp;
}emp;
void main()
{
clrscr();
printf("Enter the Emplyee details:\n");
printf("\nEnter name and emplyid:");
scanf("%s%d",emp.name,&emp.empid);
printf("\nEnter Emplyee's date of
birth:");
scanf("%d%d%d",&emp.dt.dd,&emp.dt.mm,&emp.dt.yy);
printf("\nEnter pan number and phone number:");
scanf("%s%ld",emp.pan,&emp.phone);
printf("Enter Emplyee's address details");
printf("\nEnter state, city and pin number:");
scanf("%s%s%ld",emp.add.st,emp.add.city,&emp.add.pin);
printf("\nEnter department and year of experience detail:");
scanf("%s%d",emp.dept,&emp.exp);
printf("\n");
printf("The Employee details are:\n");
printf("\nEmpluee Name:\t%s",emp.name);
printf("\nEmployee Id:\t%d",emp.empid);
printf("\nEmpluee DOB:\t%d\%d\%d",emp.dt.dd,emp.dt.mm,emp.dt.yy);
printf("\nEmployee Pan no:\t%s",emp.pan);
printf("\nEmpluee Phone number:\t%ld",emp.phone);
printf("\nEmployee Address:\t%s\t%s\t%ld",emp.add.st,emp.add.city,emp.add.pin);
printf("\nEmployee Department:\t%s",emp.dept);
printf("\nEmpluee Year of Experience:\t%d",emp.exp);
getch();
}
OUTPUT
Enter name and emplyid:abi
1
Enter Emplyee's date of birth:11 05 88
Enter pan number and phone
number:123456789 04422423567
Enter Emplyee's address details
Enter state, city and pin
number:tamilnadu chennai
600042
Enter department and year of experience
detail:cse 08
The Employee details are:
Empluee Name:
abi Employee
Id:1
Empluee DOB: 11588
Employee Pan no:
123456789
Empluee Phone number: 2147483647
Employee Address: tamilnadu chennai
600042 Employee Department: cse
Empluee Year of Experience: 8
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main()
{
char *mem_allocation;
/* memory is allocated dynamically */
mem_allocation = malloc( 20 * sizeof(char) );
if( mem_allocation== NULL )
{
printf("Couldn't able to allocate requested memory\n");
}
else
{
strcpy( mem_allocation,"Hello world");
}
printf("Dynamically allocated memory content : " \"%s\n", mem_allocation );
free(mem_allocation);
}
OUTPUT
Dynamically allocated memory content : Hello world
2. calloc() FUNCTION IN C:
calloc () function is also like malloc () function. But calloc () initializes the allocated
memory to zero. But, malloc() doesn’t.
EXAMPLE PROGRAM FOR calloc() FUNCTION
#include <stdio.h>
#include <stdlib.h>
int main () {
int i, n;
int *a;
a = (int*)calloc(n, sizeof(int));
printf("Enter %d numbers:\n",n);
for( i=0 ; i < n ; i++ ) {
scanf("%d",&a[i]);
}
printf("The numbers entered are: ");
4. free() FUNCTION IN C:
free () function frees the allocated memory by malloc (), calloc (), realloc () functions and returns the
memory to the system.
#include<stdio.h>
void main()
{
char *p;
p=(char*)malloc(6);
strcpy(p,"MADRAS");
printf("memory contains %s",p);
p=(char*)realloc(p,7);
strcpy(p,"CHENNAI");
printf("memory now contains %s",p);
free(p);
}
OUTPUT
Linked List can be defined as collection of objects called nodes that are randomly stored in the memory.
A node contains two fields i.e. data stored at that particular address and the pointer which contains the
address of the next node in the memory.
The last node of the list contains pointer to the null.
void main ()
{
int choice =0;
while(choice != 9)
{
printf("\n\n*********Main Menu*********\n");
printf("\nChoose one option from the following list ...\n");
printf("\n===============================================\n");
printf("\n1.Insert in begining\n2.Insert at last\n3.Insert at any random location\n4.Delete from
Beginning\n 5.Delete from last\n6.Delete node after specified location\n7.Search for an
element\n8.Show\n9.Exit\n");
printf("\nEnter your choice?\n");
scanf("\n%d",&choice);
switch(choice)
{
case 1:
beginsert();
break;
case 2:
lastinsert();
break;
case 3:
randominsert();
break;
case 4:
begin_delete();
break;
case 5:
last_delete();
break;
case 6:
random_delete();
break;
case 7:
search();
break;
case 8:
display();
break;
case 9:
exit(0);
break;
default:
printf("Please enter valid choice..");
}}}
void beginsert()
{
struct node *ptr;
int item;
ptr = (struct node *) malloc(sizeof(struct node *));
if(ptr == NULL)
{
printf("\nOVERFLOW");
}
else
{
printf("\nEnter value\n");
scanf("%d",&item);
ptr->data = item;
ptr->next = head;
head = ptr;
printf("\nNode inserted");
}
}
void lastinsert()
{
struct node *ptr,*temp;
int item;
ptr = (struct node*)malloc(sizeof(struct node));
if(ptr == NULL)
{
printf("\nOVERFLOW");
}
else
{
printf("\nEnter value?\n");
scanf("%d",&item);
ptr->data = item;
if(head == NULL)
{
ptr -> next = NULL;
head = ptr;
printf("\nNode inserted");
}
else
{
temp = head;
while (temp -> next != NULL)
{
temp = temp -> next;
}
temp->next = ptr;
ptr->next = NULL;
printf("\nNode inserted"); }}}
void randominsert()
{
int i,loc,item;
struct node *ptr, *temp;
ptr = (struct node *) malloc (sizeof(struct node));
if(ptr == NULL)
{
printf("\nOVERFLOW");
}
else
{
printf("\nEnter element value");
scanf("%d",&item);
ptr->data = item;
printf("\nEnter the location after which you want to insert ");
scanf("\n%d",&loc);
temp=head;
for(i=0;i<loc;i++)
{
temp = temp->next;
if(temp == NULL)
{
printf("\ncan't insert\n");
return;
}
ptr = head;
head = ptr->next;
free(ptr);
printf("\nNode deleted from the begining ...\n");
}
}
void last_delete()
{
struct node *ptr,*ptr1;
if(head == NULL)
{
printf("\nlist is empty");
}
else if(head -> next == NULL)
{
head = NULL;
free(head);
printf("\nOnly node of the list deleted ...\n");
}
else
{
ptr = head;
while(ptr->next != NULL)
{
ptr1 = ptr;
ptr = ptr ->next;
}
ptr1->next = NULL;
free(ptr);
printf("\nDeleted Node from the last ...\n");
}
}
void random_delete()
{
struct node *ptr,*ptr1;
int loc,i;
printf("\n Enter the location of the node after which you want to perform deletion \n");
scanf("%d",&loc);
ptr=head;
for(i=0;i<loc;i++)
{
ptr1 = ptr;
ptr = ptr->next;
if(ptr == NULL)
{
printf("\nCan't delete");
return;
}
}
ptr1 ->next = ptr ->next;
free(ptr);
printf("\nDeleted node %d ",loc+1);
}
void search()
{
struct node *ptr;
int item,i=0,flag;
ptr = head;
if(ptr == NULL)
{
printf("\nEmpty List\n");
}
else
{
printf("\nEnter item which you want to search?\n");
scanf("%d",&item);
while (ptr!=NULL)
{
if(ptr->data == item)
{
printf("item found at location %d ",i+1);
flag=0;
}
else
{
flag=1;
}
i++;
ptr = ptr -> next;
}
if(flag==1)
{
printf("Item not found\n");
}
}
void display()
{
struct node *ptr;
ptr = head;
if(ptr == NULL)
{
printf("Nothing to print");
}
else
{
printf("\nprinting values . . . . .\n");
while (ptr!=NULL)
{
printf("\n%d",ptr->data);
ptr = ptr -> next;
}
}
}
Output:
*********Main Menu*********
===============================================
1.Insert in begining
2.Insert at last
3.Insert at any random location
4.Delete from Beginning
5.Delete from last
6.Delete node after specified location
7.Search for an element
8.Show
9.Exit
typedef:
● 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,
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.
#include<stdio.h>
#include<string.h>
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);
}
int* x, y;
By this declaration statement, we are actually declaring x as a pointer of type int, whereas y will be declared
as a plain int variable.
struct name {
member 1;
member 2;
...
struct name *pointer;
};
The above illustrated structure prototype describes one node that comprises of two logical segments. One
of them stores data/information and the other one is a pointer indicating where the next component can
be found. .Several such inter-connected nodes create a chain of structures.
The following figure depicts the composition of such a node. The figure is a simplified illustration of
nodes that collectively form a chain of structures or linked list.
Such self-referential structures are very useful in applications that involve linked data structures,
such as lists and trees. Unlike a static data structure such as array where the number of elements that
can be inserted in the array is limited by the size of the array, a self-referential structure can
dynamically be expanded or contracted. Operations like insertion or deletion of nodes in a self-
referential structure involve simple and straight forward alteration of pointers.
EXAMPLE PROGRAM
#include<stdio.h>
#include<conio.h>
#include<alloc.h>
#include<stdlib.h>
struct node
{
int data;
struct node *next;
}*start=NULL;
void main() //Create function
{
char ch;
clrscr();
struct node *current,*new_node;
do
{
new_node=(struct node *)malloc(sizeof(struct node));
printf("\nEnter the data to create : ");
scanf("%d",&new_node->data);
new_node-next=NULL;
if(start==NULL)
{
start=new_node;
current=new_node;
}
else{
current->next=new_node;
current=new_node;}
OUTPUT
Union in C
A union is a special data type available in C that allows to store different data types
in the same memory location. You can define a union with many members, but only one
member can contain a value at any given time. Unions provide an efficient way of using the
same memory location for multiple-purpose.
Defining a Union
To define a union, you must use the union statement in the same way as you did
while defining a structure. The union statement defines a new data type with more than one
member for your program. The format of the union statement is as follows −
The union tag is optional and each member definition is a normal variable definition,
such as int i; or float f; or any other valid variable definition. At the end of the union's definition,
before the final semicolon, you can specify one or more union variables but it is optional. Here
is the way you would define a union type named Data having three members i, f, and str
union Data {
int i;
float f;
char str[20];
} data;
Now, a variable of Data type can store an integer, a floating-point number, or a string of
characters. It means a single variable, i.e., same memory location, can be used to store multiple
types of data. You can use any built-in or user defined data types inside a union based on your
requirement.
The memory occupied by a union will be large enough to hold the largest member of the union.
For example, in the above example, Data type will occupy 20 bytes of memory space because
this is the maximum space which can be occupied by a character string. The following example
displays the total memory size occupied by the above union −
#include <stdio.h>
#include <string.h>
union Data {
int i;
float f;
char str[20];
};
int main( ) {
union Data data;
return 0;
}
When the above code is compiled and executed, it produces the following result −
#include <stdio.h>
#include <string.h>
union Data {
int i;
float f;
char str[20];
};
int main( ) {
data.i = 10;
data.f = 220.5;
strcpy( data.str, "C Programming");
return 0;
}
When the above code is compiled and executed, it produces the following result −
data.i : 1917853763
data.f : 4122360580327794860452759994368.000000
data.str : C Programming
Here, we can see that the values of i and f members of union got corrupted because the final
value assigned to the variable has occupied the memory location and this is the reason that the
value of str member is getting printed very well.
Now let's look into the same example once again where we will use one variable at a time
which is the main purpose of having unions −
#include <stdio.h>
#include <string.h>
union Data {
int i;
float f;
char str[20];
};
int main( ) {
data.i = 10;
printf( "data.i : %d\n", data.i);
data.f = 220.5;
printf( "data.f : %f\n", data.f);
return 0;
}
When the above code is compiled and executed, it produces the following result −
data.i : 10
data.f : 220.500000
data.str : C Programming
Here, all the members are getting printed very well because one member is being used at a
time.
FILES
● 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 readymade structure.
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 few commands in C.
● You can easily move your data from one computer to another without any changes.
In order to understand why file handling is important, let us look at a few features of using
files:
Reusability: The data stored in the file can be accessed, updated, and deleted anywhere and
anytime providing high reusability.
Portability: Without losing any data, files can be transferred to another in the computer
system. The risk of flawed coding is minimized with this feature.
Efficient: A large amount of input may be required for some programs. File handling allows
you to easily access a part of a file using few instructions which saves a lot of time and reduces
the chance of errors.
Storage Capacity: Files allow you to store a large amount of data without having to worry
about storing everything simultaneously in a program.
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
1. 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.
2. 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.
C File Operations
C file operations refer to the different possible operations that we can perform on a
file in C such as:
Creating a new file – fopen() with attributes as “a” or “a+” or “w” or “w+”
Opening an existing file – fopen()
Reading from file – fscanf() or fgets()
Writing to a file – fprintf() or fputs()
Moving to a specific location in a file – fseek(), rewind()
Closing a file – fclose()
Open a File in C
For opening a file in C, the fopen() function is used with the filename or file path along with
the required access modes.
Syntax of fopen()
FILE* fopen(const char *file_name, const char *access_mode);
Parameters
file_name: name of the file when present in the same directory as the source file. Otherwise,
full path.
access_mode: Specifies for what operation the file is being opened.
Return Value
If the file is opened successfully, returns a file pointer to it.
If the file is not opened, then returns NULL.
Opening
Modes Description
Searches file. If the file is opened successfully fopen( ) loads it into memory and sets up
r a pointer that points to the first character in it. If the file cannot be opened fopen( ) returns
NULL.
rb Open for reading in binary mode. If the file does not exist, fopen( ) returns NULL.
Open for reading in text mode. If the file exists, its contents are overwritten. If the file
w
doesn’t exist, a new file is created. Returns NULL, if unable to open the file.
Opening
Modes Description
Open for writing in binary mode. If the file exists, its contents are overwritten. If the file
wb
does not exist, it will be created.
Searches file. If the file is opened successfully fopen( ) loads it into memory and sets up
a 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 the file.
Open for append in binary mode. Data is added to the end of the file. If the file does not
ab
exist, it will be created.
Searches file. It is opened successfully fopen( ) loads it into memory and sets up a pointer
r+
that points to the first character in it. Returns NULL, if unable to open the file.
Open for both reading and writing in binary mode. If the file does not exist, fopen( )
rb+
returns NULL.
Searches file. If the file exists, its contents are overwritten. If the file doesn’t exist a new
w+
file is created. Returns NULL, if unable to open the file.
Open for both reading and writing in binary mode. If the file exists, its contents are
wb+
overwritten. If the file does not exist, it will be created.
Searches file. If the file is opened successfully fopen( ) loads it into memory and sets up
a+ 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 the file.
Open for both reading and appending in binary mode. If the file does not exist, it will be
ab+
created.
As given above, if you want to perform operations on a binary file, then you have to append
‘b’ at the last. For example, instead of “w”, you have to use “wb”, instead of “a+” you have to
use “a+b”.
Example of Opening a File
int main()
{
// file pointer variable to store the value returned by
// fopen
FILE* fptr;
Output
The file is not opened. The program will now exit.
The file is not opened because it does not exist in the source directory. But the fopen() function
is also capable of creating a file if it does not exist. It is shown below
Create a File in C
The fopen() function can not only open a file but also can create a file if it does not exist already.
For that, we have to use the modes that allow the creation of a file if not found such as w, w+,
wb, wb+, a, a+, ab, and ab+.
FILE *fptr;
fptr = fopen("filename.txt", "w");
Example of Opening a File
Output
The file is created Successfully.
Function Description
fscanf() Use formatted string and variable arguments list to take input from a file.
So, it depends on you if you want to read the file line by line or character by character.
Example:
FILE * fptr;
fptr = fopen(“fileName.txt”, “r”);
fscanf(fptr, "%s %s %s %d", str1, str2, str3, &year);
char c = fgetc(fptr);
The getc() and some other file reading functions return EOF (End Of File) when they reach the
end of the file while reading. EOF indicates the end of the file and its value is implementation-
defined.
Note: One thing to note here is that after reading a particular part of the file, the file pointer
will be automatically moved to the end of the last read character.
Write to a File
The file write operations can be performed by the functions fprintf() and fputs() with
similarities to read operations. C programming also provides some other functions that can be
used to write data to a file such as:
Function Description
Similar to printf(), this function use formatted string and varible arguments list to
fprintf()
print output to the file.
fputs() Prints the whole line in the file and a newline at the end.
fwrite() This functions write the specified amount of bytes to the binary file.
#include <stdio.h>
void main()
{
FILE *fptr;
int id;
char name[30];
float salary;
fptr = fopen("emp.txt", "w+");/* open for writing */
if (fptr == NULL)
{
printf("File does not exists \n");
return;
}
printf("Enter the id\n");
scanf("%d", &id);
fprintf(fptr, "Id= %d\n", id);
printf("Enter the name \n");
scanf("%s", name);
fprintf(fptr, "Name= %s\n", name);
printf("Enter the salary\n");
scanf("%f", &salary);
fprintf(fptr, "Salary= %.2f\n", salary);
fclose(fptr);
}
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
Example:
#include <stdio.h>
main(){
FILE *fp;
fp = fopen("file1.txt", "w");//opening file
fputc('a',fp);//writing single character into file
fclose(fp);//closing file
}
file1.txt
a
Reading File : fgetc() function
The fgetc() function returns a single character from the file. It gets a character from the stream.
It returns EOF at the end of file.
Syntax:
int fgetc(FILE *stream)
Example:
#include<stdio.h>
#include<conio.h>
void main(){
FILE *fp;
char c;
clrscr();
fp=fopen("myfile.txt","r");
while((c=fgetc(fp))!=EOF){
printf("%c",c);
}
fclose(fp);
getch();
}
myfile.txt
this is simple text message
Closing a File
The fclose() function is used to close the file. After successful file operations, you must always
close a file to remove it from the memory.
Syntax of fclose()
fclose(file_pointer);
where the file_pointer is the pointer to the opened file.
Example:
FILE *fptr ;
fptr= fopen(“fileName.txt”, “w”);
C fseek() function
The fseek() function is used to set the file pointer to the specified offset. It is used to write data
into file at desired location.
Syntax:
int fseek(FILE *stream, long int offset, int whence)
There are 3 constants used in the fseek() function for whence: SEEK_SET, SEEK_CUR and
SEEK_END.
Example:
#include <stdio.h>
void main(){
FILE *fp;
fp = fopen("myfile.txt","w+");
fputs("This is javatpoint", fp);
fseek( fp, 7, SEEK_SET );
fputs("sonoo jaiswal", fp);
fclose(fp);
}
myfile.txt
This is sonoo jaiswal
C rewind() function
The rewind() function sets the file pointer at the beginning of the stream. It is useful if you have
to use stream many times.
Syntax:
void rewind(FILE *stream)
Example:
File: file.txt
this is a simple text
File: rewind.c
#include<stdio.h>
#include<conio.h>
void main(){
FILE *fp;
char c;
clrscr();
fp=fopen("file.txt","r");
while((c=fgetc(fp))!=EOF)
{
printf("%c",c);
}
Output
The file is now opened.
Data successfully written in file GfgTest.c
The file is now closed.
This program will create a file named GfgTest.c in the same directory as the source file which
will contain the following text: “GeeksforGeeks-A Computer Science Portal for Geeks”.
Example 2: Program to Open a File, Read from it, And Close the File
Output
The file is now opened.
GeeksforGeeks-A Computer Science Portal for Geeks
Data successfully read from file GfgTest.c
The file is now closed.
This program reads the text from the file named GfgTest.c which we created in the previous
example and prints it in the console.
fclose(fptr);
return 0;
}
Output
Write Operation Successful
return 0;
}
Output
n1: 1 n2: 5 n3: 6
n1: 2 n2: 10 n3: 11
n1: 3 n2: 15 n3: 16
n1: 4 n2: 20 n3: 21
More Functions for C File Operations
The following table lists some more functions that can be used to perform file operations or
assist in performing them.
Functions Description
• Sequential
• Random access.
Sequential files are generally used in cases where the program processes the data in a sequential
fashion – i.e. counting words in a text file – although in some cases, random access can be
feigned by moving backwards and forwards over a sequential file.
True random access file handling, however, only accesses the file at the point at which the data
should be read or written, rather than having to process it sequentially. A hybrid approach is
also possible whereby a part of the file is used for sequential access to locate something in the
random access portion of the file, in much the same way that a File Allocation Table (FAT)
works.
fread(&i,sizeof(int),1,fp);
sum=num[i]+sum;
}
avg=sum/n;
printf("\n the average of numbers is is %d", avg);
fclose(fp);
getch();
}
Pointer position:
This sets the pointer position in the file.
Value pointer position
0 Beginning of file.
1 Current position
2 End of file
The origin parameter can be one of three values:
• SEEK_SET – from the start;
• SEEK_CUR – from the current position;
• SEEK_END – from the end of the file. So, the equivalent of rewind() would be:
fseek( f, 0, SEEK_SET);
Example:
1) fseek( p,10L,0)
0 means pointer position is on beginning of the file,from this statement pointer position is
skipped 10 bytes from the beginning of the file.
2) fseek( p,5L,1)
1 means current position of the pointer position.From this statement pointer position is skipped
5 bytes forward from the current position.
3) fseek(p,-5L,1)
ftell()
This function returns the value of the current pointer position in the file.The value is count from
the beginning of the file.
Syntax: ftell(fptr); Where fptr is a file pointer.
rewind() This function is used to move the file pointer to the beginning of the given
file.
Syntax: rewind( fptr); Where fptr is a file pointer.
Example program for fseek():
Write a program to read last ‘n’ characters of the file using appropriate file functions(Here we
need fseek() and fgetc()).
#include<stdio.h>
#include<conio.h>
void main()
{
FILE *fp;
char ch;
clrscr();
fp=fopen("file1.c", "r");
if(fp==NULL)
printf("file cannot be opened");
else
{
printf("Enter value of n to read last ‘n’ characters");
scanf("%d",&n);
fseek(fp,-n,2);
while((ch=fgetc(fp))!=EOF)
{
printf("%c\t",ch);
}}
fclose(fp); getch();
}
OUTPUT: It depends on the content in the file.
#include <stdio.h>
int main( int argc, char *argv[] ) {
if( argc == 2 ) {
printf("The argument supplied is %s\n", argv[1]);
}
else if( argc > 2 ) {
printf("Too many arguments supplied.\n");
}
else {
printf("One argument expected.\n");
}
}
When the above code is compiled and executed with single argument, it produces the following
result.
$./a.out testing
The argument supplied is testing
When the above code is compiled and executed with a two arguments, it produces the following
result.
$./a.out testing1 testing2
Too many arguments supplied.
When the above code is compiled and executed without passing any argument, it produces the
following result.
$./a.out
One argument expected
It should be noted that argv[0] holds the name of the program itself and argv[1] is a pointer to
the first command line argument supplied, and *argv[n] is the last argument. If no arguments
are supplied, argc will be one, and if you pass one argument then argc is set at 2.
You pass all the command line arguments separated by a space, but if argument itself has a
space then you can pass such arguments by putting them inside double quotes "" or single
quotes ''.
Let us re-write above example once again where we will print program name and we also pass
a command line argument by putting inside double quotes −
#include <stdio.h>
int main( int argc, char *argv[] ) {
printf("Program name %s\n", argv[0]);
if( argc == 2 ) {
printf("The argument supplied is %s\n", argv[1]);
}
else if( argc > 2 ) {
printf("Too many arguments supplied.\n");
}
else {
printf("One argument expected.\n");
}
}
When the above code is compiled and executed with a single argument separated by space but
inside double quotes, it produces the following result.
$./a.out "testing1 testing2"
Program name ./a.out
The argument supplied is testing1 testing2
Example:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) // command line arguments
{
if(argc!=5)
{
printf("Arguments passed through command line " \ "not equal to 5");
return 1;
}
printf("\n Program name : %s \n", argv[0]);
printf("1st arg : %s \n", argv[1]);
printf("2nd arg : %s \n", argv[2]);
printf("3rd arg : %s \n", argv[3]);
printf("4th arg : %s \n", argv[4]);
printf("5th arg : %s \n", argv[5]);
return 0;
}
OUTPUT:
Program name : test.c 1st arg : this
2nd arg : is
3rd arg : a
4th arg : program 5th arg : (null)
Example:
#include <stdio.h>
int main( int argc, char *argv[] )
{
if( argc == 2 )
{
printf("The argument supplied is %s\n", argv[1]);
}
else if( argc > 2 )
{
printf("Too many arguments supplied.\n");
}
else
{
printf("One argument expected.\n");
}
}
OUTPUT:
One argument expected C:\TURBOC3>BIN\cd.. C:\TURBOC3>cd SOURCE
C:\TURBOc3\SOURCE>cmd.exe testing The argument supplied is testing
C:\TURBOc3\SOURCE>cmd.exe testing testing1 Too many arguments supplied