0% found this document useful (0 votes)
10 views

c concepts

Uploaded by

Santhosh kumar S
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

c concepts

Uploaded by

Santhosh kumar S
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 30

UNIT- 4

COLLECTIVE DATA TYPES AND FILE HANDLING


4.1 STRUCTURES
4.1.1 INTRODUCTION TO STRUCTURE IN C
1. As we know that Array is collection of the elements of same type, but many time we
have to store the elements of the different data types.
2. Suppose Student record is to be stored, then for storing the record we have to group
together all the information such as Roll name, Percent which may be of different data
types.
3. Ideally Structure is collection of different variables under single name.
4. Basically Structure is for storing the complicated data.
5. A structure is a convenient way of grouping several pieces of related information
together.
4.1.2 Structure Initialization:
The members of the structure can be initialized to constant valued by enclosing the values
to be assigned within the braces after the structure definition
struct date{
int date;
int month;
int year;
} republic= {26, 1, 1950};
Initializes the member variable data, month, year of republic to 26, 1, 1950 respectively.
4.1.3 DEFINITION OF STRUCTURE IN C:
Structure is composition of the different variables of different data types, grouped under
same name.
typedef struct {
char name[64];
char course[128];
int age;
int year; } student;
Some Important Definitions of Structures:
1. Each member declared in Structure is called member.
char name[64];
char course[128];
int age; int year;
2. Name given to structure is called as tag
student
3. Structure member may be of different data type including user defined data-type also
typedef struct {
char name[64];
char course[128];
book b1;
int year;
} student;
Here book is user defined data type.
4.1.4 STRUCTURE DECLARATION
In C we can group some of the user defined or primitive data types together and form
another compact way of storing complicated information is called as Structure. Let us see how to
declare structure in c programming language -
Structure Alternate Syntax :
Syntax Of Structure in C Programming:
struct <structure_name>
struct tag
{
{
structure_Element1;
data_type1 member1;
structure_Element2;
data_type2 member2;
...
data_type3 member3; };
};
Some Important Points Regarding Structure in C Programming:
1. Struct keyword is used to declare structure.
2. Members of structure are enclosed within opening and closing braces.
3. Declaration of Structure reserves no space.
4. It is nothing but the “Template / Map / Shape” of the structure.
5. Memory is created, very first time when the variable is created /Instance is created.
Different Ways of Declaring Structure Variable:
Way 1 : Immediately after Structure Template
struct date
{
int date;
char month[20];
int year;
}today;
// 'today' is name of Structure variable
Way 2 : Declare Variables using struct Keyword
struct date
{
int date;
char month[20];
int year;
};
struct date today;
Where “date” is name of structure and “today” is name of variable.
Way 3: Declaring Multiple Structure Variables
struct Book
{
int pages;
char name[20];
int year;
} book1, book2, book3;
We can declare multiple variables separated by comma directly after closing curly.
4.1.5 Arrays of Structures:
Arrays of structures are commonly used in a large number of similar records required to
be processed together. If there were one hundred employees in an organization , this data can be
organized in an array of structures. consider the following example:
struct emp-data
{
char name[30];
int age; };

Then the array of structure used is


struct emp-data employee[100];
the first record is referred as employee[0], second record is referred by employee[1], and so on.
employee *0+.name = “raja1”
employee[0].age = 25
employee*1+.name = “raja3”
employee[1].age = 35
hence array of structures is used to manage large number of records easily.
Array within structures:
A structure can have an array within it.
Char name[30]; //Like this is a structure can have no. of arrays as members.
Eg:
Struct student
{
char name[25];
int sem;
char branch[10];
int mark[3];
}
In the above example there are four members. Out of these four fields, name, branch and
mark are arrays.
4.1.6 STRUCTURE WITHIN STRUCTURE: NESTED STRUCTURE
A structure within structure means nesting of structures. a structure can be declared
within another structure. Consider the following emp-data structure. In this case the structure
‘date’ may be placed
inside the structure.
struct date{
int date,month,year;
};
struct emp-data
{
char name[30];
struct date dob;
};
Example
main()
{
struct emp-data raja=,“raja”,,14,8,90--;
printf(“%s”,raja.name);
printf(“%d%d%d”,raja.dob.date,raja.dob.month, raja.dob.year);
}
4.1.7 Structure and functions
This method is to pass each member of the structure as an actual arguments of the
function call. The actual arguments are then treated independently ordinary variables. This is the
most elementary methods and becomes inefficient when the structure size is large.
Syntax:
Function name (Structure variable name)
#include<stdio.h>
struct student
{
int sub1;
int sub2;
int sub3;
};
void main()
{
struct student s[10];
int i,total=0;
clrscr();
for(i=0;i<=2;i++)
{
printf("\nEnter Marks in Three Subjects = ");
scanf("%d%d%d",& s[i].sub1,&s[i].sub2,&s[i].sub3);
total=s[i].sub1+s[i].sub2+s[i].sub3;
printf("\nTotal marks of s[%d] Student= %d",i,total);
}
getch();
}

4.2 UNION
Unions are quite similar to the structures in C. Union is also a derived type as structure.
Union can be defined in same manner as structures just the keyword used in defining union in
union where keyword used in defining structure was struct.
union car{
char name[50];
int price;
};
Union variables can be created in similar manner as structure variable.

union car{
union car{
char name[50];
char name[50];
OR int price;
int price;
};
}c1, c2, *c3;
-------Inside Function-----------
union car c1, c2, *c3;

In both cases, union variables c1, c2 and union pointer variable c3 of type union car is
created.
Accessing members of an union
The member of unions can be accessed in similar manner as that structure. Suppose, we
you want to access price for union variable c1 in above example, it can be accessed as c1.price.
If you want to access price for union pointer variable c3, it can be accessed as (*c3).price or as
c3->price.
Union:
Union is another compound data type like structure. Union is used to minimize memory
utilization. In structure each member has the separate storage location. but in union all the
members share the common place of memory. so a union can handle only one member at a time.
Declaration of Union:
The general format for declaring union is,
union tagname
{
datatype member1;
datatype member2;
..
...
datatype member N;
};
Where union is the keyword. Tag name is any user defined data types.
Example:
union personal
{
char name[25];
int age;
float height;
};
In the above example ‘union bio’ has 3 members first member is a character array ‘name’
having to 10 character (10 bytes)second member is an integer ‘ age’ that requires 2 bytes third
member is a float as four bytes, all the three members are different data types.
Here all these 3 members are allocated with common memory . That means, the compiler
allocates a piece of storage that is large enough to hold the all type in the union.
In case of structure it will be occupies a separate memory of each data types.
Advantages:
1. It is used to minimize memory utilization.
2. it is used to convert data from one type to another type.
Example:
union test
{
int sum;
float average;
};
EX. 4.1 PROGRAMS USING STRUCTURES AND UNIONS
C Program to Store Information of Single Variable
#include <stdio.h>
struct student{
char name[50];
int roll;
float marks;
};
int main(){
struct student s;
printf("Enter information of students:\n\n");
printf("Enter name: ");
scanf("%s",s.name);
printf("Enter roll number: ");
scanf("%d",&s.roll);
printf("Enter marks: ");
scanf("%f",&s.marks);
printf("\nDisplaying Information\n");
printf("Name: %s\n",s.name);
printf("Roll: %d\n",s.roll);
printf("Marks: %.2f\n",s.marks);
return 0;
}
EX 4.2 Source Code to Store Information of 10 students Using Structure
#include <stdio.h>
struct student{
char name[50];
int roll;
float marks;
};
int main(){
struct student s[10];
int i;
printf("Enter information of students:\n");
for(i=0;i<10;++i)
{
s[i].roll=i+1;
printf("\nFor roll number %d\n",s[i].roll);
printf("Enter name: ");
scanf("%s",s[i].name);
printf("Enter marks: ");
scanf("%f",&s[i].marks);
printf("\n");
}
printf("Displaying information of students:\n\n");
for(i=0;i<10;++i)
{
printf("\nInformation for roll number %d:\n",i+1);
printf("Name: ");
puts(s[i].name);
printf("Marks: %.1f",s[i].marks);
}
return 0;
}
Output
Enter information of students:
For roll number 1
Enter name: Tom
Enter marks: 98
For roll number 2
Enter name: Jerry
Enter marks: 89
.
Displaying information of students:
Information for roll number 1:
Name: Tom
Marks: 98
Source Code Demonstrate the Dynamic Memory Allocation for Structure
#include <stdio.h>
#include<stdlib.h>
struct name {
int a;
char c[30];
};
int main(){
struct name *ptr;
int i,n;
printf("Enter n: ");
scanf("%d",&n);
/* allocates the memory for n structures with pointer ptr pointing to the base address. */
ptr=(struct name*)malloc(n*sizeof(struct name));
for(i=0;i<n;++i){
printf("Enter string and integer respectively:\n");
scanf("%s%d",&(ptr+i)->c, &(ptr+i)->a);
}
printf("Displaying Infromation:\n");
for(i=0;i<n;++i)
printf("%s\t%d\t\n",(ptr+i)->c,(ptr+i)->a);
return 0;
}
Output
Enter n: 2
Enter string and integer respectively:
Programming
22
Enter string, integer and floating number respectively:
Structure
33
Displaying Information:
Programming 22 Memory allocation in structures
Structure 33
Program to demonstrate UNION Name Salary Worker no
#include <stdio.h> 32 bytes 4 bytes 4 bytes
Union job { //defining a union
char name[32];
float salary;
int worker_no; Memory allocation in union
}u;
Struct job1 { Name
char name[32]; 32 bytes
float salary;
int worker_no;
}s;
int main(){
printf("size of union = %d",sizeof(u));
printf("\nsize of structure = %d", sizeof(s));
return 0;
}
Output
Size of union = 32
Size of structure = 40
There is difference in memory allocation between union and structure as suggested in
above example. The amount of memory required to store a structure variables is the sum of
memory size of all members. But, the memory required to store a union variable is the memory
required for largest element of an union.
4.2 Enumeration (or enum) in C
Enumeration (or enum) is a user defined data type in C. It is mainly used to assign names to
integral constants, the names make a program easy to read and maintain.

enum State {Working = 1, Failed = 0};


The keyword ‘enum’ is used to declare new enumeration types in C and C++. Following is an
example of enum declaration.
The name of enumeration is "flag" and the constant
// are the values of the flag. By default, the values
// of the constants are as follows:
// constant1 = 0, constant2 = 1, constant3 = 2 and
// so on.
enum flag{constant1, constant2, constant3, ....... };

Variables of type enum can also be defined. They can be defined in two ways:
// In both of the below cases, "day" is
// defined as the variable of type week.

enum week{Mon, Tue, Wed};


enum week day;

// Or

enum week{Mon, Tue, Wed}day;

enum week{Mon, Tue, Wed, Thur, Fri, Sat, Sun};

int main()

enum week day;

day = Wed;

printf("%d",day);

return 0;

Output:
2
In the above example, we declared “day” as the variable and the value of “Wed” is allocated to
day, which is 2. So as a result, 2 is printed.
#include<stdio.h>

enum year{Jan, Feb, Mar, Apr, May, Jun, Jul,


Aug, Sep, Oct, Nov, Dec};

int main()
{
int i;
for (i=Jan; i<=Dec; i++)
printf("%d ", i);

return 0;
}

Output:
0 1 2 3 4 5 6 7 8 9 10 11
In this example, the for loop will run from i = 0 to i = 11, as initially the value of i is Jan which is
0 and the value of Dec is 11.
4.3 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
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.
typedef unsigned int unit;
In the above statements, we have declared the unit variable of type unsigned int by using a
typedef keyword.
Now, we can create the variables of type unsigned int by writing the following statement:
unit a, b;
instead of writing:
unsigned int a, b;
Till now, we have observed that the typedef keyword provides a nice shortcut by providing an
alternative name for an already existing variable. This keyword is useful when we are dealing
with the long data type especially, structure declarations.
Let's understand through a simple example.
#include <stdio.h>
int main()
{
typedef unsigned int unit;
unit i,j;
i=10;
j=20;
printf("Value of i is :%d",i);
printf("\nValue of j is :%d",j);
return 0;
}
Output
Value of i is :10
Value of j is :20
Using typedef with structures
Consider the below structure declaration:
struct student
{
char name[20];
int age;
};
struct student s1;
In the above structure declaration, we have created the variable of student type by writing the
following statement:
struct student s1;
The above statement shows the creation of a variable, i.e., s1, but the statement is quite big. To
avoid such a big statement, we use the typedef keyword to create the variable of type student.
struct student
{
char name[20];
int age;
};
typedef struct student stud;
stud s1, s2;
In the above statement, we have declared the variable stud of type struct student. Now, we can
use the stud variable in a program to create the variables of type struct student.
The above typedef can be written as:
typedef struct student
{
char name[20];
int age;
} stud;
stud s1,s2;
From the above declarations, we conclude that typedef keyword reduces the length of the code
and complexity of data types. It also helps in understanding the program.
4.4 Self Referential Structures
Self Referential structures are those structures that have one or more pointers which point to the
same type of structure, as their member.
struct node {
int data1;
char data2;
struct node* link;
};

int main()
{
struct node ob;
return 0;
}
In the above example ‘link’ is a pointer to a structure of type ‘node’. Hence, the structure
‘node’ is a self-referential structure with ‘link’ as the referencing pointer.
An important point to consider is that the pointer should be initialized properly before
accessing, as by default it contains garbage value.
Types of Self Referential Structures

1. Self Referential Structure with Single Link


2. Self Referential Structure with Multiple Links
Self Referential Structure with Single Link: These structures can have only one self-pointer
as their member. The following example will show us how to connect the objects of a self-
referential structure with the single link and access the corresponding data members. The
connection formed is shown in the following figure.
Self Referential Structure with Multiple Links: Self referential structures with
multiple links can have more than one self-pointers. Many complicated data
structures can be easily constructed using these structures. Such structures
can easily connect to more than one nodes at a time. The following example
shows one such structure with more than one links.
The connections made in the above example can be understood using the
following figure.

Applications:
Self referential structures are very useful in creation of other complex data structures like:
 Linked Lists
 Stacks
 Queues
 Trees
 Graphs etc
4.5 FILE HANDLING AND MANIPULATION IN C
File
File is a place on disk where a group of related data is stored. Abstractly, a file is a
collection of bytes stored on a secondary storage device, which is generally a disk of some kind.
The collection of bytes may be interpreted, for example, as characters, words, lines, paragraphs
and pages from a textual document, fields and records belonging to a database, or pixels from a
graphical image.
Why files are needed?
When the program is terminated, the entire data is lost in C programming. If you want to keep
large volume of data, it is time consuming to enter the entire data. But, if file is created, these
information can be accessed using few commands. Depending upon the way file is opened for
processing, a file is classified into:
1. Text file
2. Binary file
File Operations
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 file
Creating a File:
While working with file, you need to declare a pointer of type file. This declaration is
needed for communication between file and program.
FILE *ptr;
Opening a File:
Opening a file is performed using library function fopen(). The syntax for opening a file in
standard I/O is:
ptr=fopen("fileopen","mode")
For Example:
fopen("E:\\cprogram\program.txt","w");
E:\\cprogram\program.txt is the location to create file.
"w" represents the mode for writing.

Opening Modes in Standard I/O

File Mode Meaning of Mode During Inexistence of file

R Open for reading. If the file does not exist, fopen() returns NULL.

W Open for writing. If the file exists, its contents are overwritten. If
the file does not exist, it will be created.

A Open for append. i.e, Data is If the file does not exists, it will be created.
added to end of file.

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

w+ Open for both reading and If the file exists, its contents are overwritten. If
writing. the file does not exist, it will be created.
a+ Open for both reading and If the file does not exists, it will be created.
appending.

Closing a File
The file should be closed after reading/writing of a file. Closing a file is performed using
library function fclose().
fclose(ptr); //ptr is the file pointer associated with file to be closed.
The Functions fprintf() and fscanf() functions.
The functions fprintf() and fscanf() are the file version of printf() and fscanf(). The only
difference while using fprintf() and fscanf() is that, the first argument is a pointer to the structure
FILE
Writing to a file
#include <stdio.h>
int main()
{
int n;
FILE *fptr;
fptr=fopen("C:\\program.txt","w");
if(fptr==NULL){
printf("Error!");
exit(1);
}
printf("Enter n: ");
scanf("%d",&n);
fprintf(fptr,"%d",n);
fclose(fptr);
return 0;
}
This program takes the number from user and stores in file. 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 that file, you can see the integer you entered.
Similarly, fscanf() can be used to read data from file.
Reading from file
#include <stdio.h>
int main()
{
int n;
FILE *fptr;
if ((fptr=fopen("C:\\program.txt","r"))==NULL){
printf("Error! opening file");
exit(1); /* Program exits if file pointer returns NULL. */
}
fscanf(fptr,"%d",&n);
printf("Value of n=%d",n);
fclose(fptr);
return 0;
}
If you have run program above to write in file successfully, you can get the integer back
entered in that program using this program.
Other functions like fgetchar(), fputc() etc. can be used in similar way.
EX: Write a C program to read name and marks of n number of students from user and store
them in a file
#include <stdio.h>
int main(){
char name[50];
int marks,i,n;
printf("Enter number of students: ");
scanf("%d",&n);
FILE *fptr;
fptr=(fopen("C:\\student.txt","w"));
if(fptr==NULL){
printf("Error!");
exit(1);
}
for(i=0;i<n;++i)
{
printf("For student%d\nEnter name: ",i+1);
scanf("%s",name);
printf("Enter marks: ");
scanf("%d",&marks);
fprintf(fptr,"\nName: %s \nMarks=%d \n",name,marks);
}
fclose(fptr);
return 0;
}
Ex 2: Write a C program to read name and marks of n number of students from user and store
them in a file. If the file previously exits, add the information of n students.
#include <stdio.h>
int main(){
char name[50];
int marks,i,n;
printf("Enter number of students: ");
scanf("%d",&n);
FILE *fptr;
fptr=(fopen("C:\\student.txt","a"));
if(fptr==NULL){
printf("Error!");
exit(1);
}
for(i=0;i<n;++i)
{
printf("For student%d\nEnter name: ",i+1);
scanf("%s",name);
printf("Enter marks: ");
scanf("%d",&marks);
fprintf(fptr,"\nName: %s \nMarks=%d \n",name,marks);
}
fclose(fptr);
return 0;
}
Input/Output operation on File

C provides a number of functions that helps to perform basic file operations. Following are the
functions,

Function description

fopen() create a new file or open a existing file

fclose() closes a file

getc() reads a character from a file

putc() writes a character to a file

fscanf() reads a set of data from a file

fprintf() writes a set of data to a file

getw() reads a integer from a file

putw() writes a integer to a file


In the above table we have discussed about various file I/O functions to perform reading
and writing on file.getc() and putc() are simplest functions used to read and write individual
characters to a file.
#include<stdio.h>
#include<conio.h>
main()
{
FILE *fp;
char ch;
fp = fopen("one.txt", "w");
printf("Enter data");
while( (ch = getchar()) != EOF) {
putc(ch,fp);
}
fclose(fp);
fp = fopen("one.txt", "r");
while( (ch = getc()) != EOF)
printf("%c",ch);
fclose(fp);
}
Make sure you have /tmp directory available. If it is not, then before proceeding, you must create
this directory on your machine.
#include <stdio.h>
main() {
FILE *fp; When the above code is compiled and executed, it
reads the file created in the previous section and
fp = fopen("/tmp/test.txt", "w+"); produces the following result −
fprintf(fp, "This is testing for fprintf...\n"); 1 : This
fputs("This is testing for fputs...\n", fp); 2: is testing for fprintf...
fclose(fp); 3: This is testing for fputs...
}
Binary files
Binary files are very similar to arrays of structures, except the structures are in a disk-file
rather than an array in memory. Binary files have two features that distinguish them from text
files:
▪ You can instantly use any structure in the file.
▪ You can change the contents of a structure anywhere in the file.
Opening modes of binary files
rb, rb+, wb, wb+, ab and ab+. Here, the b is appended to indicate that, it is a binary file.
▪ After you have opened the binary file, you can read and write a structure or seek a
specific position in the file. A file position indicator points to record 0 when the file is
opened.
▪ A read operation reads the structure where the file position indicator is pointing to. After
reading the structure the pointer is moved to point at the next structure.
▪ A write operation will write to the currently pointed-to structure. After the write
operation the file position indicator is moved to point at the next structure.
▪ The fseek function will move the file position indicator to the record that is requested.
▪ Remember that you keep track of things, because the file position indicator can not only
point at the beginning of a structure, but can also point to any byte in the file.
The fread and fwrite function takes four parameters:
▪ A memory address
▪ Number of bytes to read per block
▪ Number of blocks to read
▪ A file variable
For example:
fread (&my_record,sizeof(struct rec),1,ptr_myfile);
This fread() statement says to read x bytes (size of rec) from the file ptr_myfile into
memory address &my_record. Only one block is requested. Changing the one into ten will read
in ten blocks of x bytes at once.
Let’s look at a write example:
#include<stdio.h>
struct rec /* Our structure */
{
int x,y,z; };
int main()
{
int counter;
FILE *ptr_myfile;
struct rec my_record;
ptr_myfile=fopen("test.bin","wb");
if (!ptr_myfile)
{
printf("Unable to open file!");
return 1;
}
for ( counter=1; counter <= 10; counter++)
{
my_record.x= counter;
fwrite(&my_record, sizeof(struct rec), 1, ptr_myfile);
}
fclose(ptr_myfile);
return 0;
}
In this example we declare a structure rec with the members x,y and z of the type integer.
In the main function we open (fopen) a file for writing (w). Then we check if the file is open, if
not, an error message is displayed and we exit the program. In the “for loop” we fill the structure
member x with a number. Then we write the record to the file. We do this ten times, thus
creating ten records. After writing the ten records, we will close the file (don’t forget this).
So now we have written to a file, let’s read from the file we have just created. Take a
look at the example:
#include<stdio.h>
struct rec /* Our structure */
{
int x,y,z; };
int main()
{ int counter;
FILE *ptr_myfile;
struct rec my_record;
ptr_myfile=fopen("test.bin","rb");
if (!ptr_myfile)
{
printf("Unable to open file!");
return 1;
}
for ( counter=1; counter <= 10; counter++)
{
fread(&my_record,sizeof(struct rec),1,ptr_myfile);
printf("%d\n",my_record.x);
}
fclose(ptr_myfile);
return 0;
}
The only two lines that are changed are the two lines in the “for loop”. With the fread we
read-in the records (one by one). After we have read the record we print the member x (of that
record).
The only thing we need to explain is the fseek option. The function fseek must be
declared like this:
int fseek(FILE * stream, long int offset, int whence);
The fseek function sets the file position indicator for the stream pointed to by the stream.
The new position, measured in characters from the beginning of the file, is obtained by adding
offset to the position specified by whence. Three macros are declared in stdio.h called:
SEEK_SET, SEEK_CUR and SEEK_END.
If the position declared by whence is SEEK_SET, then the position is the beginning of the file.
The SEEK_END can be used if you want to go to the end of the file. (Using negative
numbers it is possible to move from the end of the file.)
If whence is SEEK_CUR then the position is set, x bytes, from the current position.
Let’s take a look at an example:
#include<stdio.h>
struct rec /* Our structure */
{
int x,y,z;
};
int main()
{
int counter;
FILE *ptr_myfile;
struct rec my_record;

ptr_myfile=fopen("test.bin","rb");
if (!ptr_myfile)
{
printf("Unable to open file!");
return 1;
}
for ( counter=9; counter >= 0; counter--)
{
fseek(ptr_myfile,sizeof(struct rec)*counter,SEEK_SET);
fread(&my_record,sizeof(struct rec),1,ptr_myfile);
printf("%d\n",my_record.x);
}
fclose(ptr_myfile);
return 0;
}
In this example we are using fseek to seek the last record in the file. This record we read
with fread statement and with the printf statement we print member x of the structure my_record.
As you can see the “for loop” also changed. The “for loop” will now countdown to zero. This
counter is then used in the fseek statement to set the file pointer at the desired record. The result
is that we read-in the records in the reverse order.
A last note: if you set the file position indicator to a position in a file and you want the
first position in a file then you can use the function rewind to the first position in the file. The
function rewind can be used like this:
#include<stdio.h>
struct rec /* Our structure */
{
int x,y,z;
};
int main()
{
int counter;
FILE *ptr_myfile;
struct rec my_record;
ptr_myfile=fopen("test.bin","rb");
if (!ptr_myfile)
{
printf("Unable to open file!");
return 1;
}
fseek(ptr_myfile, sizeof(struct rec), SEEK_END);
rewind(ptr_myfile);
for ( counter=1; counter <= 10; counter++)
{
fread(&my_record,sizeof(struct rec),1,ptr_myfile);
printf("%d\n",my_record.x);
}
fclose(ptr_myfile);
return 0;
}
With the fseek statement in this example we go to the end of the file. Then we rewind to
first position in the file. Then read-in all records and print the value of member x. Without the
rewind you will get garbage

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy