C-Structures, Unions, File Handiling

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 27

Structures

Structures (also called structs) are a way to group several related variables into
one place. Each variable in the structure is known as a member of the
structure.
Unlike an array, a structure can contain many different data types (int, float,
char, etc.).
Create a Structure
1. struct structure_name
2. {
3.
4. data_type member1;
5. data_type member2;
6. .
7. .
8. data_type memeberN;
9. };
Let's see the example to define a structure for an entity employee in c.
1. struct employee
2. { int id;
3. char name[20];
4. float salary;
5. };
Declaring structure variable
We can declare a variable for the structure so that we can access the member
of the structure easily. There are two ways to declare structure variable:
1. By struct keyword within main() function
2. By declaring a variable at the time of defining the structure.
1st way:
Let's see the example to declare the 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;
The variables e1 and e2 can be used to access the values stored in the
structure. Here, e1 and e2 can be treated in the same way as the objects in C+
+ and Java.

2nd way:
Let's see another way to declare variable at the time of defining the structure.
1. struct employee
2. { int id;
3. char name[50];
4. float salary;
5. }e1,e2;

Accessing members of the structure


There are two ways to access structure members:
1. By . (member or dot operator)
2. By -> (structure pointer operator)

#include <stdio.h>
// Create a structure called myStructure
struct myStructure {
int myNum;
char myLetter;
};
int main() {
// Create a structure variable of myStructure called s1
struct myStructure s1;
// Assign values to members of s1
s1.myNum = 13;
s1.myLetter = 'B';
// Print values
printf("My number: %d\n", s1.myNum);
printf("My letter: %c\n", s1.myLetter);
return 0;
}

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. //store second employee information
15. e2.id=102;
16. strcpy(e2.name, "James Bond");
17. e2.salary=126000;
18. //printing first employee information
19. printf( "employee 1 id : %d\n", e1.id);
20. printf( "employee 1 name : %s\n", e1.name);
21. printf( "employee 1 salary : %f\n", e1.salary);
22.
23. //printing second employee information
24.
25. printf( "employee 2 id : %d\n", e2.id);
26. printf( "employee 2 name : %s\n", e2.name);
27. printf( "employee 2 salary : %f\n", e2.salary);
28. return 0;
29.}

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

typedef in C

The typedef is a keyword used in C programming to provide some meaningful


names to the already existing variable in the C program. It behaves similarly as
we define the alias for the commands. In short, we can say that this keyword is
used to redefine the name of an already existing variable.

Syntax of typedef
1. typedef <existing_name> <alias_name>

In the above syntax, 'existing_name' is the name of an already existing variable


while 'alias name' is another name given to the existing variable.

For example, suppose we want to create a variable of type unsigned int, then
it becomes a tedious task if we want to declare multiple variables of this type.
To overcome the problem, we use a typedef keyword.

Let's understand through a simple example.


1. #include <stdio.h>
2. int main()
3. {
4. typedef unsigned int unit;
5. unit i,j;
6. i=10;
7. j=20;
8. printf("Value of i is :%d",i);
9. printf("\nValue of j is :%d",j);
10.return 0;
11.}

Output

Value of i is :10
Value of j is :20

Using typedef with structures


1. #include <stdio.h>
2. typedef struct student
3. {
4. char name[20];
5. int age;
6. }stud;
7. int main()
8. {
9. stud s1;
10.printf("Enter the details of student s1: ");
11.printf("\nEnter the name of the student:");
12.scanf("%s",&s1.name);
13.printf("\nEnter the age of student:");
14.scanf("%d",&s1.age);
15.printf("\n Name of the student is : %s", s1.name);
16.printf("\n Age of the student is : %d", s1.age);
17.return 0;
18.}

Output

Enter the details of student s1:


Enter the name of the student: Peter
Enter the age of student: 28
Name of the student is : Peter
Age of the student is : 28
C Array of Structures

Why use an array of structures?

Consider a case, where we need to store the data of 5 students. We can store
it by using the structure as given below.
1. #include<stdio.h>
2. struct student
3. {
4. char name[20];
5. int id;
6. float marks;
7. };
8. void main()
9. {
10. struct student s1,s2,s3;
11. int dummy;
12. printf("Enter the name, id, and marks of student 1 ");
13. scanf("%s %d %f",s1.name,&s1.id,&s1.marks);
14. scanf("%c",&dummy);
15. printf("Enter the name, id, and marks of student 2 ");
16. scanf("%s %d %f",s2.name,&s2.id,&s2.marks);
17. scanf("%c",&dummy);
18. printf("Enter the name, id, and marks of student 3 ");
19. scanf("%s %d %f",s3.name,&s3.id,&s3.marks);
20. scanf("%c",&dummy);
21. printf("Printing the details....\n");
22. printf("%s %d %f\n",s1.name,s1.id,s1.marks);
23. printf("%s %d %f\n",s2.name,s2.id,s2.marks);
24. printf("%s %d %f\n",s3.name,s3.id,s3.marks);
25.}

Output

Enter the name, id, and marks of student 1 James 90 90


Enter the name, id, and marks of student 2 Adoms 90 90
Enter the name, id, and marks of student 3 Nick 90 90
Printing the details....
James 90 90.000000
Adoms 90 90.000000
Nick 90 90.000000

In the above program, we have stored data of 3 students in the structure.


However, the complexity of the program will be increased if there are 20
students. In that case, we will have to declare 20 different structure variables
and store them one by one. This will always be tough since we will have to
declare a variable every time we add a student. Remembering the name of all
the variables is also a very tricky task. However, c enables us to declare an
array of structures by using which, we can avoid declaring the different
structure variables; instead we can make a collection containing all the
structures that store the information of different entities.
Array of Structures in C

An array of structres in C can be defined as the collection of multiple structures


variables where each variable contains information about different entities.
The array of structures in C are used to store information about multiple
entities of different data types. The array of structures is also known as the
collection of structures.

Let's see an example of an array of structures that stores information of 5


students and prints it.
1. #include<stdio.h>
2. #include <string.h>
3. struct student{
4. int rollno;
5. char name[10];
6. };
7. int main(){
8. int i;
9. struct student st[5];
10.printf("Enter Records of 5 students");
11.for(i=0;i<5;i++){
12.printf("\nEnter Rollno:");
13.scanf("%d",&st[i].rollno);
14.printf("\nEnter Name:");
15.scanf("%s",&st[i].name);
16.}
17.printf("\nStudent Information List:");
18.for(i=0;i<5;i++){
19.printf("\nRollno:%d, Name:%s",st[i].rollno,st[i].name);
20.}
21. return 0;
22.}
Output:

Enter Records of 5 students


Enter Rollno:1
Enter Name:Sonoo
Enter Rollno:2
Enter Name:Ratan
Enter Rollno:3
Enter Name:Vimal
Enter Rollno:4
Enter Name:James
Enter Rollno:5
Enter Name:Sarfraz

Student Information List:


Rollno:1, Name:Sonoo
Rollno:2, Name:Ratan
Rollno:3, Name:Vimal
Rollno:4, Name:James
Rollno:5, Name:Sarfraz

Structure Pointer in C
A structure pointer is defined as the pointer which points to the address of the
memory block that stores a structure known as the structure pointer. Complex
data structures like Linked lists, trees, graphs, etc. are created with the help of
structure pointers. The structure pointer tells the address of a structure in
memory by pointing the variable to the structure variable.
Example:

 C
// C program to demonstrate structure pointer
#include <stdio.h>
struct point {
int value;
};
int main()
{
struct point s;
// Initialization of the structure pointer
struct point* ptr = &s;
return 0;
}

In the above code s is an instance of struct point and ptr is the struct pointer
because it is storing the address of struct point.

Accessing the Structure Member with the Help of Pointers

There are two ways to access the members of the structure with the help of a
structure pointer:
1. With the help of (*) asterisk or indirection operator and (.) dot operator.
2. With the help of ( -> ) Arrow operator.
Below is the program to access the structure members using the structure
pointer with the help of the dot operator.

// C Program to demonstrate Structure pointer


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

struct Student {
int roll_no; guv
char name[30];
char branch[40];
int batch;
};
int main()
{
struct Student s1;
struct Student* ptr = &s1;

s1.roll_no = 27;
strcpy(s1.name, "Kamlesh Joshi");
strcpy(s1.branch, "Computer Science And Engineering");
s1.batch = 2019;

printf("Roll Number: %d\n", (*ptr).roll_no);


printf("Name: %s\n", (*ptr).name);
printf("Branch: %s\n", (*ptr).branch);
printf("Batch: %d", (*ptr).batch);

return 0;
}

C Program to demonstrate Structure to Functions


#include <stdio.h>
struct student {
char name[50];
int per,rno;
};

int main() {
struct student s1;

printf("Enter name: ");


gets(s1.name);
printf("Enter the roll number: ");
scanf("%d",&s1.rno);
printf("Enter percentage: ");
scanf("%d", &s1.per);
display(s1.rno,s1.per);
return 0;
}

void display(int a, int b ) {


printf("\nDisplaying information\n");
printf("Roll number: %d", a);
printf("\nPercentage: %d", b);
}

C - Unions

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 −
union [union tag] {
member definition;
member definition;
...
member definition;
} [one or more union variables];
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;
printf( "Memory size occupied by data : %d\n", sizeof(data));
return 0;
}

When the above code is compiled and executed, it produces the following
result −

Memory size occupied by data : 20

Accessing Union Members

To access any member of a union, we use the member access operator (.). The
member access operator is coded as a period between the union variable
name and the union member that we wish to access. You would use the
keyword union to define variables of union type. The following example shows
how to use unions in a program −
#include <stdio.h>
#include <string.h>
union Data {
int i;
float f;
char str[20];
};
int main( ) {
union Data data;
data.i = 10;
data.f = 220.5;
strcpy( data.str, "C Programming");
printf( "data.i : %d\n", data.i);
printf( "data.f : %f\n", data.f);
printf( "data.str : %s\n", data.str);

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 −
Live Demo
#include <stdio.h>
#include <string.h>

union Data {
int i;
float f;
char str[20];
};
int main( ) {
union Data data;
data.i = 10;
printf( "data.i : %d\n", data.i);
data.f = 220.5;
printf( "data.f : %f\n", data.f);
strcpy( data.str, "C Programming");
printf( "data.str : %s\n", data.str);
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.
Enum in C

The enum in C is also known as the enumerated type. It is a user-defined data


type that consists of integer values, and it provides meaningful names to these
values. The use of enum in C makes the program easy to understand and
maintain. The enum is defined by using the enum keyword.

Why do we use enum?


The enum is used when we want our variable to have only a set of values. For
example, we create a direction variable. As we know that four directions exist
(North, South, East, West), so this direction variable will have four possible
values. But the variable can hold only one value at a time. If we try to provide
some different value to this variable, then it will throw the compilation error.

The following is the way to define the enum in C:

1. enum flag{integer_const1, integer_const2,.....integter_constN};

In the above declaration, we define the enum named as flag containing 'N'
integer constants. The default value of integer_const1 is 0, integer_const2 is 1,
and so on. We can also change the default value of the integer constants at the
time of the declaration.

For example:

1. enum fruits{mango, apple, strawberry, papaya};

The default value of mango is 0, apple is 1, strawberry is 2, and papaya is 3. If


we want to change these default values, then we can do as given below:

1. enum fruits{
2. mango=2,
3. apple=1,
4. strawberry=5,
5. papaya=7,
6. };
Enumerated type declaration

As we know that in C language, we need to declare the variable of a pre-


defined type such as int, float, char, etc. Similarly, we can declare the variable
of a user-defined data type, such as enum. Let's see how we can declare the
variable of an enum type.

Suppose we create the enum of type status as shown below:

1. enum status{false,true};

Now, we create the variable of status type:


1. enum status s; // creating a variable of the status type.

In the above statement, we have declared the 's' variable of type status.

To create a variable, the above two statements can be written as:

1. enum status{false,true} s;

In this case, the default value of false will be equal to 0, and the value of true
will be equal to 1.

Let's create a simple program of enum.


1. #include <stdio.h>
2. enum weekdays{Sunday=1, Monday, Tuesday, Wednesday, Thursday, Friday, S
aturday};
3. int main()
4.
5. {
6. enum weekdays w; // variable declaration of weekdays type
7. w=Monday; // assigning value of Monday to w.
8. printf("The value of w is %d",w);
9. return 0;
10.}
Output

Let's demonstrate another example to understand the enum more clearly.


1. #include <stdio.h>
2. enum months{jan=1, feb, march, april, may, june, july, august, september, oct
ober, november, december};
3. int main()
4. {
5. // printing the values of months
6. for(int i=jan;i<=december;i++)
7. {
8. printf("%d, ",i);
9. }
10. return 0;
11.}

Output
The enum is also used in a switch case statement in which we pass the enum
variable in a switch parenthesis. It ensures that the value of the case block
should be defined in an enum.

Let's see how we can use an enum in a switch case statement.

1. #include <stdio.h>
2. enum days{sunday=1, monday, tuesday, wednesday, thursday, friday, saturday
};
3. int main()
4. {
5. enum days d;
6. d=monday;
7. switch(d)
8. {
9. case sunday:
10. printf("Today is sunday");
11. break;
12. case monday:
13. printf("Today is monday");
14. break;
15. case tuesday:
16. printf("Today is tuesday");
17. break;
18. case wednesday:
19. printf("Today is wednesday");
20. break;
21. case thursday:
22. printf("Today is thursday");
23. break;
24. case friday:
25. printf("Today is friday");
26. break;
27. case saturday:
28. printf("Today is saturday");
29. break;
30. }
31. return 0;
32.}
Output

C File Handling

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. Reading from and writing information to a file

4. Closing 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 Modes in Standard I/O

Mode Meaning of Mode During Inexistence of file

If the file does not exist, fopen() returns


r Open for reading.
NULL.

Open for reading If the file does not exist, fopen() returns
rb
in binary mode. 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


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

Open for append.


Data is added to If the file does not exist, it will be
a
the end of the created.
file.

Open for append


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

Open for both


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

rb+ Open for both If the file does not exist, fopen() returns
reading and NULL.
writing in binary
Opening Modes in Standard I/O

Mode Meaning of Mode During Inexistence of file

mode.

If the file exists, its contents are


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

Open for both If the file exists, its contents are


reading and overwritten.
wb+
writing in binary If the file does not exist, it will be
mode. created.

Open for both


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

Open for both


reading and If the file does not exist, it will be
ab+
appending in created.
binary mode.

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.
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.
#include <stdio.h>
#include <stdlib.h>

int main()
{
int num;
FILE *fptr;
// use appropriate location if you are using MacOS or Linux
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;
}
Example 2: Read from a text file
#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;
}

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

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("C:\\program.bin","wb")) == NULL){
printf("Error! opening file");

// Program exits if the file po


inter 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;
}
Reading from a binary file

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


above.
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("C:\\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;
}

Random Access File in C

The C programming language offers a variety of functions that enable working


with random access file in C, which grant programmers the ability to read from
or write to any position within the file. This article will delve deeper into the
concept of random access file in C and explore its functionalities.

What are Files?

In programming languages, files are utilized for long-term data storage or data
transfer purposes. The method of accessing a file varies depending on the type
of file system employed to retrieve data stored within the file.

Types of Files

Sequential files and random access files are two common ways of organizing
data in computer systems.

Sequential file:

Sequential file is a type of file organization in which data is stored in a


continuous manner, one record after the other, and each record is accessed in
sequence. In a sequential file, data is read from the beginning of the file and is
processed in the order it appears in the file. This type of file is best suited for
applications where data is processed sequentially and not randomly accessed.

Random Access file:

In C language, a random access file allows us to read or write any data in our
disc file without reading or writing every piece of data before it. We can quickly
search for data, edit it, or even delete it in a random-access file. We can open
and close random access files in C using the same opening mode as sequential
files, but we need a few new functions to access files randomly.

Functions in random access file:

Thus, the following three functions assist in accessing the random access file
in C:

1. ftell()

2. fseek()

3. rewind()

1. ftell():

It is a standard C library function used to get the current position of the file
pointer in a random access file. The function takes a file pointer as its
argument and returns the current position of the file pointer, representing the
number of bytes from the beginning of the file.

Syntax for ftell():

pos=ftell(FILE *fp)

Explanation of Syntax for ftell():


Where pos contain the current position or the number of bytes read, and fp is
a file pointer.

Example for ftell():

include<stdio.h>
int main()
{
FILE *fp;
fp=fopen("prepbytes.txt","r");
if(!fp)
{
printf("Error: File cannot be opened\n") ;
return 0;
}
printf("Position pointer in the beginning : %ld\n",ftell(fp));
char ch;
while(fread(&ch,sizeof(ch),1,fp)==1)
{
printf("%c",ch);
}
printf("\nSize of file in bytes is : %ld\n",ftell(fp));
fclose(fp);
return 0;
}

Output:

Position pointer in the beginning : 0

prepbytes

Size of file in bytes is : 9

Explanation for ftell():


First, let us create a file – prepbytes.txt which contains the data: prepbytes.We
can observe that in the beginning, ftell returns 0 as the pointer points to the
beginning and after traversing completely we print each character of the file till
the end, and now ftell returns 9 as it is the size of the file.

2. fseek():

The fseek() function is a standard library function in the C programming


language. It is used to set the file position indicator to a specified position in a
file, allowing the program to read or write data from that position.

Syntax for fseek():

int fseek(FILE *fp, long offset, int whence);

Explanation of Syntax for fseek():


Here, stream is a pointer to the file stream that needs to be positioned, offset
is the number of bytes to offset from the specified position, and whence is the
origin from which to measure the offset. The function returns zero if the
operation is successful, and a nonzero value if an error occurs.
The whence argument can be one of the following constants:

 SEEK_SET: The offset is relative to the beginning of the file.

 SEEK_CUR: The offset is relative to the current position in the file.

 SEEK_END: The offset is relative to the end of the file.

When fseek() is called, it sets the file position indicator to the specified position
in the file associated with the stream pointer. The offset argument specifies
the number of bytes to offset from the origin specified by whence.This
function is typically used in programs that need to read or write data from a
specific position in a file, such as when searching for a particular piece of data
in a large file or when appending data to the end of a file.

Example for fseek():

 c

#include<stdio.h>
int main()
{
FILE *fp;
fp = fopen("prepbytes.txt","r");
if(!fp)
{
printf("Error: File cannot be opened\n");
return 0;
}
fseek(fp, 4, 0);
char ch;
while(fread(&ch,sizeof(ch),1,fp)==1)
{
printf("%c",ch);
}
fclose(fp);
return 0;
}

Output:

bytes

Explanation for fseek():


First, let us create a file – prepbytes.txt which contains the data: prepbytes.We
can observe that when fseek(fp,4,0) the pointer moves to the 5th byte in the
file, or we can say 4 bytes forward from the beginning, So when we traverse
the file from that position, we receive output as bytes.
3. rewind():

The rewind() function is a standard library function in C programming


language. It is used to set the file position indicator to the beginning of a file,
allowing the file to be read from the start again.

Syntax for rewind():

rewind(FILE *fp);

Explanation of Syntax for rewind():


Here, the stream is a pointer to the file stream that needs to be rewound. The
function does not return any value. When rewind() is called, it sets the file
position indicator to the beginning of the file associated with the stream
pointer. Any previous errors or end-of-file conditions are cleared, allowing the
file to be read from the start again. This function is typically used in programs
that read data from a file multiple times, such as when processing a text file. By
rewinding the file to the beginning, the program can read the data again
without having to close and reopen the file.

Example for rewind():

#include<stdio.h>
int main()
{
FILE *fp;
fp = fopen("prepbytes.txt","r");
if(!fp)
{
printf("Error in opening file\n");
return 0;
}
printf("Position of the pointer : %ld\n",ftell(fp));
char ch;
while(fread(&ch,sizeof(ch),1,fp)==1)
{ printf("%c",ch);
}
printf("Position of the pointer : %ld\n",ftell(fp));
rewind(fp);
printf("Position of the pointer : %ld\n",ftell(fp));
fclose(fp);
return 0;
}

Output:

Position of the pointer : 0

prepbytes

Position of the pointer: 9

Position of the pointer : 0

Explanation of rewind():
First, let us create a file – prepbytes.txt which contains the data: prepbytes.
We can observe that firstly when ftell is called, it returns 0 as the position of
the pointer is at the beginning, and then after traversing the file, when ftell is
called, 9 is returned, which is the size of the file. Now when rewind(fp) is
called, the pointer will move to its original position, which is 0. So the last ftell
returns 0

You might also like