Professional Documents
Culture Documents
UNIT- II
C PROGRAMMING - ADVANCED FEATURES
Structures – Union – Enumerated Data Types – Pointers: Pointers to Variables, Arrays and Functions
– File Handling – Preprocessor Directives.
STRUCTURE:
A Structure is a collection of different data types that are stored under a common name.
It is a user-defined data type.
Syntax:
struct tag_name
{
datatype element_1;
datatype element_2;
…
datatype element_n;
} variable_1, variable_2, variable_3;
struct is a keyword, which declares a structure.
tag_name is called as, the name of a structure.
datatype element_1, datatype element_2 and so on are called as structure members which is of
different data types.
variable_1, variable_2, .., variable_n are called as structure variables.
Only by using this structure variables we can access the structure members.
Example:
struct student
{ // structure template
int rollno;
char name[100];
char address[100];
}s1,s2,s3; // structure declaration
FEATURES OF STRUCTURES:
1.The structure elements are stored in successive memory locations.
2.Nesting of structure is possible.
3.It is also possible pass structure elements to a function.
4.One can pass individual structure as a function argument by value or address.
NEED FOR STRUCTURE DATA TYPE:
1.Structure in C allows us to combine different data types to store a particular type of record.
2.Structure helps to construct a complex data type in more meaningful way.
3.It is somewhat similar to an Array. The only difference is that array is used to store collection of similar
data types while structure can store collection of different data types.
4.Structure is used to represent a record. Suppose you want to store record of Student which consists of
student name, address, roll number and age. we can define a structure to hold this information.
Structure Declaration:
struct book
{
char title[10];
int pages;
float price;
};
1
CS3353- C PROGRAMMING AND DATA STRUCTURES UNIT-II C PROGRAMMING –ADVANCED FEATURES
2
CS3353- C PROGRAMMING AND DATA STRUCTURES UNIT-II C PROGRAMMING –ADVANCED FEATURES
char city[20];
int pincode;
}
};
Example program for employee details using structure
#include<stdio.h>
struct Address
{
char HouseNo[25];
char City[25];
char PinCode[25];
};
struct Employee
{
int IdNo;
char Name[25];
float Salary;
struct Address Add;
};
void main()
{
int i;
struct Employee E;
printf("\n\tEnter Employee Id : ");
scanf("%d",&E.IdNo);
printf("\n\tEnter Employee Name : ");
scanf("%s",&E.Name);
printf("\n\tEnter Employee Salary : ");
scanf("%f",&E.Salary);
printf("\n\tEnter Employee House No : ");
scanf("%s",&E.Add.HouseNo);
printf("\n\tEnter Employee City : ");
scanf("%s",&E.Add.City);
printf("\n\tEnter Employee House No : ");
scanf("%s",&E.Add.PinCode);
printf("\nDetails of Employees");
printf("\n\tEmployee IdNo : %d",E.IdNo);
printf("\n\tEmployee Name : %s",E.Name);
printf("\n\tEmployee Salary : %f",E.Salary);
printf("\n\tEmployee House No : %s",E.Add.HouseNo);
printf("\n\tEmployee City : %s",E.Add.City);
printf("\n\tEmployee House No : %s",E.Add.PinCode);
}
Output :
Enter Employee IdNo : 101
Enter Employee Name : Suresh
Enter Employee Salary : 45000
3
CS3353- C PROGRAMMING AND DATA STRUCTURES UNIT-II C PROGRAMMING –ADVANCED FEATURES
4
CS3353- C PROGRAMMING AND DATA STRUCTURES UNIT-II C PROGRAMMING –ADVANCED FEATURES
struct student
{
char name[10][10];
int rollno,m1,m2,m3,total;
};
void main()
{
int num,i,j;
struct student s1[10];
clrscr();
printf("enter the number of students\n");
scanf("%d",&num);
for(i=0;i<num;i++)
{
printf("enter the rollno");
scanf("%d",&s1[i].rollno);
printf("enter the name");
scanf("%s",s1[i].name);
printf("enter the mark1");
scanf("%d",&s1[i].m1);
printf("enter the mark2");
scanf("%d",&s1[i].m2);
printf("enter the mark3");
scanf("%d",&s1[i].m3);
s1[i].total=s1[i].m1+s1[i].m2+s1[i].m3;
}
printf("\n the details of the mark list is as follows\n");
printf("\n Roll no");
printf("\t Name");
printf("\t Mark 1");
printf("\t Mark 2");
printf("\t Mark 3");
printf("\t Total");
printf("\n");
for(i=0;i<num;i++)
{
printf("\n%d",s1[i].rollno);
printf("\t%s",s1[i].name);
printf("\t%d",s1[i].m1);
printf("\t%d",s1[i].m2);
printf("\t%d",s1[i].m3);
s1[i].total=s1[i].m1+s1[i].m2+s1[i].m3;
printf("\t%d",s1[i].total);
}
getch();
}
5
CS3353- C PROGRAMMING AND DATA STRUCTURES UNIT-II C PROGRAMMING –ADVANCED FEATURES
Output:
Enter the Number of students: 2
Enter the Roll number : 01
Enter the Name : Raja
Enter the Mark1 : 98
Enter the Mark1 : 95
Enter the Mark1 : 85
}s;
1. In above example, it declares “s” variable of type union.
2. The union contains three members as data type of int, char, float.
3. We can use only one of them at a time.
Memory allocation :
6
CS3353- C PROGRAMMING AND DATA STRUCTURES UNIT-II C PROGRAMMING –ADVANCED FEATURES
void main()
{
int num,i,da=5,pf=1500;
clrscr();
printf("Enter the no of the Employee \n");
scanf("%d",&num);
for(i=0;i<num;i++)
{
printf("\n enter the employee number");
scanf("%d",&emp[i].empno);
printf("\n the employee number : %d",emp[i].empno);
printf("\n enter the employee name");
scanf("%s",&emp[i].name);
printf("\nthe employee name :%s",emp[i].name);
printf("\n enter the basic pay");
scanf("%d",&emp[i].bpay);
printf("the basic pay:%d",emp[i].bpay);
emp[i].netpay= emp[i].bpay +(emp[i].bpay*da/100)-pf;
printf("the net pay:%f",emp[i].netpay);
}
}
POINTER TO STRUCTURE:
Variable may be of any datatype like int,float,double.
We can define pointer to structure. Here starting address of the member variable can be accessed.
Ex :
Struct book
{
Char name[25];
Char author[25];
7
CS3353- C PROGRAMMING AND DATA STRUCTURES UNIT-II C PROGRAMMING –ADVANCED FEATURES
Int pages;
};
Struct book *ptr;
Here *ptr is pointer to structure book. 1. Ptr->name 2.ptr->author 3. Ptr->pages.
Write a program to declare pointer to structure and display the contents of the structure.
void main()
{
struct book
{
char name[25];
char author[25];
int pages;
};
struct book b1={“c programming”,”ashok”,500};
struct book *ptr;
ptr=&b1;
clrscr();
printf(“%s by %s of %d pages”,b1.name,b1.author,b1.pages);
printf(“%s by %s of %d pages”,ptr->name,ptr->author,ptr->pages);
getch();
}
STRUCTURE AND FUNCTION :
Structure variables can be passed to the function by value or address
Structure element is to be passed to any other function it is essential to declare the structure outside the
main() function that is global structure. They can accessed by all other functions.
Ex:
struct book
{
char name[25];
char author[25];
int pages;
};
void main()
{
struct book b1={“c programming”,”ashok”,500};
show(&b1);
getch();
}
show(struct book *b2)
{
Clrscr();
Printf(“%s by %s of %d pages”,b2->name,b2->author,b2->pages);
}
POINTERS:
A pointer is a memory variable that stores a memory address of another variable.
Pointer variable is denoted by prefixing ‘*’ (asterisk) operator.
Eg: int *ptr.
8
CS3353- C PROGRAMMING AND DATA STRUCTURES UNIT-II C PROGRAMMING –ADVANCED FEATURES
In the above program ‘ptr’ is a pointer variable that holds the address of the variable ‘x’
‘&’ operator will give the address of a particular variable.
‘*ptr’ will retrieve the value of the address it holds, that why it is called as dereferencing operator.
USES OF POINTERS:
Pointers save memory space.
Execution time with the pointer is faster.
The memory is accessed efficiently with pointers.
Dynamic memory allocation is possible using pointers
Pointers are used with data structures.
Pointers are used in the file handling.
Write a program to add two numbers through variables and their pointers.
void main()
{
inta,b,c,d,*ap,*bp;
printf(“enter the 2 number”);
scanf(“%d %d”,&a,&b);
ap=&a;
bp=&b;
c=a+b;
d=*ap+*bp;
printf(“the sum of a,b using value =%d”,c);
pintf(“the sum of a,b using pointer %d”,d);
}
9
CS3353- C PROGRAMMING AND DATA STRUCTURES UNIT-II C PROGRAMMING –ADVANCED FEATURES
10
CS3353- C PROGRAMMING AND DATA STRUCTURES UNIT-II C PROGRAMMING –ADVANCED FEATURES
return 0;
}
Output
Value of var[0] = 10
Value of var[1] = 100
Value of var[2] = 200
FUNCTION AND POINTERS:
Write the example program of call by reference page no: unit I - 32
POINTER TO POINTER:
The pointer is known as a variable containing address of another variable.
The pointer variable containing address of another pointer variable is known as pointer to pointer. The
chain can be continued to any extend.
‘p1′ that points to yet another pointer ‘p2′ that points to a character ‘ch’. In memory, the three variables
can be visualized.
So we can see that in memory, pointer p1 holds the address of pointer p2. Pointer p2 holds the address of
character ‘ch’.
So ‘p2′ is pointer to character ‘ch’, while ‘p1′ is pointer to ‘p2′ or we can also say that ‘p2′ is a pointer to
pointer to character ‘ch’.
Now, in code ‘p2′ can be declared as : char *p2 = &ch;
But ‘p1′ is declared as : char **p1 = &p2;
So we see that ‘p1′ is a double pointer (ie pointer to a pointer to a character) and hence the two *’s are
used in declaration.
Example program
void main()
{
int a=2,*p,**q;
p=&a;
q=&p;
clrscr();
printf(“value a= %d address of a=%u”,a,&a);
printf(“value of *p=%d address of *p=%u”,*p,p);
printf(“value of**q=%d address of q=%u”,**q,*q);
}
POINTER AND STRINGS :
A string is collection of characters that are stored in the character array. Every string is terminated with the
‘\0’(null character end of every string)
Ex :
Char arr[ ] = { ‘a’,’a’,’m’,’e’,’c’,’\0’};
void main()
{
11
CS3353- C PROGRAMMING AND DATA STRUCTURES UNIT-II C PROGRAMMING –ADVANCED FEATURES
charstr[20],*s;
int p=0,q=0;
clrscr();
printf(“enter string”);
gets(str);
s=str;
while (*s!=’\0’)
{
printf(“%c”,*s);
p++;
s++;
if (*s = = 32)
q++;
}
printf(“length of string including space = %d “,p);
printf(“length of string excluding space=%d”,p-q);
}
VOID POINTERS:
1.In C General Purpose Pointer is Called as void Pointer.
2.It does not have any data type associated with it
3.It can store address of any type of variable
4.A void pointer is a C convention for a raw address.
5.The compiler has no idea what type of object a void Pointer “really points to.” ?
Declaration of Void Pointer :
void * pointer_name;
Void Pointer Example :
void*ptr;// ptr is declared as Void pointer
charcnum;
intinum;
floatfnum;
ptr=&cnum;// ptr has address of character data
ptr=&inum;// ptr has address of integer data
ptr=&fnum;// ptr has address of float data
Explanation :
void*ptr;
We have declared 3 variables of integer, character and float type.
When we assign address of integer to the void pointer, pointer will become Integer Pointer.
When we assign address of Character Data type to void pointer it will become Character Pointer.
Similarly we can assign address of any data type to the void pointer.
It is capable of storing address of any data type
ENUMERATED DATA TYPE:
The enumerated data type is a user-defined type based on the standard integer type.
An enumeration consists of a set of named integer constants.
Each integer value is assigned an identifier.
12
CS3353- C PROGRAMMING AND DATA STRUCTURES UNIT-II C PROGRAMMING –ADVANCED FEATURES
This identifier (which is also known as an enumeration constant) can be used as a symbolic name to make
the program more readable.
Enumerations create new data types to contain values that are not limited to the values that fundamental
data types may take.
Syntax:
enum enumeration_name { identifier1, identifier2 , , ...identifiern };
The enum keyword is basically used to declare and initialize a sequence of integer constants.
Here, enumeration_ name is optional.
Example:
Creates a new type of variable called COLORS to store colour constants.
enum COLORS {RED, BLUE,BLACK,GREEN,YELLOW,PURPLE,WHITE};
In case you do not assign any value to a constant , the default value of RED is 0, BLUE is 1, BLACK is
2, and so on.
However, you can also change these default values while declaring the enum.
#include<stdio.h>
int main( )
{
enum {RED=2, BLUE,BLACK=5,GREEN=7,YELLOW,PURPLE,WHITE=15};
printf("\n RED = %d", RED);
printf("\n BLUE = %d", BLUE);
printf("\n BLACK =%d", BLACK);
printf("\n GREEN = %d”, GREEN);
printf("\n YELLOW=%d", YELLOW);
printf("\n PURPLE = %d", PURPLE);
printf('\n WHITE=%d", WHITE);
return 0;
}
Output:
RED = 2
BLUE = 3
BLACK = 5
GREEN = 7
YELLOW = 8
PURPLE = 9
WHITE = 15
RULES APPLY TO THE MEMBERS OF AN ENUMERATION LIST:
An enumeration list may contain duplicate constant values.
Therefore, two different identifiers may be assigned the same value, say 3.
The identifiers in the enumeration list must be different from other identifiers in the same scope with the
same visibility including ordinary variable names and identifiers in other enumeration lists.
Enumeration names follow the normal scoping rules. So every enumeration name must be different from
other enumeration, structure, and union names with the same visibility.
Anonymous enumerated type:
If we create an enumerated type without enumeration_name, it is known as an anonymous enumerated
type.
Example: enum {OFF, ON};
13
CS3353- C PROGRAMMING AND DATA STRUCTURES UNIT-II C PROGRAMMING –ADVANCED FEATURES
declares an enumerated type that has two constants OFF with a value 0 and ON with a value 1.
enum Variables:
We have seen that enumerated constants are basically integers, so programs with statements such as int
fore_color = RED; is considered to be a legal statement in C .
In extension to this, C also permits the user to declare variables of an enumerated data type in the same
way as we create variables of other basic data types.
Syntax:
enumeration_name variable_name;
So to create a variable of COLORS, we may write
enum COLORS bg_color;
This declares a variable called bg_ color, which is of the enumerated data type, COLORS.
Another way to declare a variable can be as illustrated in the following statement.
enum COLORS {RED, BLUE, BLACK, GREEN, YELLOW, PURPLE, WHITE} bg_color , fore_color;
Using the typedef keyword:
Example: If we write,
typedef enum COLORS color;
Then we can straightaway declare variables by writing
Color forecolor = RED;
ASSIGNING VALUES TO ENUMERATED DATATYPE:
Once the enumerated variable has been declared, values can be stored in it.
However ,an enumerated variable can hold only declared values for the type.
Example, to assign the colour black to the background color, we will
bg_color = BLACK;
Note that once an enumerated variable has been assigned a value, we can store its value in another variable
of the same type.
. Example:
enum COLORS bg_color , border_color;
bg_color = BLACK;
border_color = bg_color;
ENUMERATION TYPE CONVERSION:
Enumerated types can be implicitly or explicitly cast.
For example, the compiler can implicitly cast an enumerated type to an integer when required.
However, when we implicitly cast an integer to an enumerated type, the compiler will either generate an
error or a warning message.
To remove the error, you can do either of two things.
First, declare c to be an int.
Second, cast the right-hand side in the following manner.
enum COLORS {RED, BLUE, BLACK, GREEN, YELLOW, PURPLE, WHITE};
enum COLORS c;
c = BLACK ; // valid in C
c = 2 ; // illegal in C
c = ( enum COLORS ) 2 ; // Right way
COMPARING ENUMERATED TYPES:
C also allows using comparison operators on enumerated data type.
bg_color = (enum COLORS)6;
if(bg_color == WHITE)
14
CS3353- C PROGRAMMING AND DATA STRUCTURES UNIT-II C PROGRAMMING –ADVANCED FEATURES
fore_color = BLUE;
fore_color = BLACK;
if(bg_color == fore_color)
printf (“\n NOT VISIBLE “ ) ;
Since enumerated types are derived from integer type, they can be used in a switch case statement.
Example:
enum {RED, BLUE, BLACK, GREEN, YELLOW, PURPLE, WHITE}bg_color;
switch (bg_color)
case RED:·
case BLUE:
case GREEN:
printf("\n It is a primary color" );
break;
case default:
printf("\n It is not a primary color");
break;
}
Input/Output Operations on Enumerated Types:
Since enumerated types are derived types, they cannot be read or written using formatted input/output
functions available in the C language.
When we read or write an enumerated type, we read/write it as an integer.
enum COLORS {RED, BLUE, BLACK, GREEN, YELLOW, PURPLE, WHITE};
enum COLORS c;
scanf (“ %d”, &c);
printf (“\n Color = %d”,c);
PREPROCESSOR DIRECTIVES:
The preprocessor is a program that process the source program before it is passed to the compiler.
It starts with # (symbol) before main() function and there is no semicolon with end.
The program typed in the editor is the source code to the preprocessor.
It is passed to the compiler.
Preprocessor can reduce the execution time of a program
1. #define Directive (or MACRO)
It is used to define some constants
• Syntax
# define identifier string/integer
• Example:
#define pi 3.14
#define CITY “chennai”
PI as macro template and 3.14 as macro substitute.
Macro templates are generally declared with capital letter, it can also small letters.
Identifiers are not a keyword can use valid variables.
Example1: Example2:
#include<stdio.h> #define PI 3.14
#include<conio.h> #define max 2
#define pi 3.14 #define cls clrscr()
#define CITY "chennai" #define display printf()
15
CS3353- C PROGRAMMING AND DATA STRUCTURES UNIT-II C PROGRAMMING –ADVANCED FEATURES
void main()
{
clrscr();
#if defined (a)
printf(“macro found”);
#else
#error macro is not defined
#endif
}
FILE HANDLING IN C:
Real life situations involve large volume of data and in such cases, the console oriented I/O operations
pose two major problems.
It becomes cumbersome and time consuming to handle large volumes of data through terminals.
The entire data is lost when either the program is terminated or computer is turned off therefore it is
necessary to have more flexible approach where data can be stored on the disks and read whenever
necessary, without destroying the data. This method employs the concept of files to store data.
File is defined as a set of records, containing numbers, symbols and text that can be accessed through
various file functions.
There are two types of files namely, sequential file and random access file.
In sequential access file systems, records are stored in sequential manner.
To access the nth record, all the records starting from 0 to n-1 need to be accessed.
In random access file system, a record can be read and modified at random.
C supports a number of functions that have the ability to perform basic file operations, which include:
1. Naming a file
2. Opening a file
3. Reading from a file
4. Writing data into a file
5. Closing a file
File operation functions in C:
Function Name Operation
Creates a new file for use
fopen ( )
Opens a new existing file for use
fclose ( ) Closes a file which has been opened for use
getc ( ) Reads a character from a file
putc ( ) Writes a character to a file
fprintf ( ) Writes a set of data values to a file
fscanf ( ) Reads a set of data values from a file
getw ( ) Reads a integer from a file
putw ( ) Writes an integer to the file
fseek ( ) Sets the position to a desired point in the file
ftell ( ) Gives the current position in the file
rewind() Sets the position to the begining of the file
Defining and opening a file:
If we want to store data in a file into the secondary memory, we must specify certain things about the file
to the operating system.
They include the fielname, data structure, purpose.
17
CS3353- C PROGRAMMING AND DATA STRUCTURES UNIT-II C PROGRAMMING –ADVANCED FEATURES
18
CS3353- C PROGRAMMING AND DATA STRUCTURES UNIT-II C PROGRAMMING –ADVANCED FEATURES
printf(“%c”,c);
fclose(f1);
}
The getw and putw functions:
/*Example program for using getw and putw functions*/
#include< stdio.h >
main( )
{
FILE *f1,*f2,*f3;
int number I;
printf(“Contents of the data filen \n”);
f1=fopen(“DATA”,”W”);
for(I=1;I< 30;I++)
{
scanf(“%d”,&number);
if(number = = -1)
break;
putw(number,f1);
}
fclose(f1);
f1=fopen(“DATA”,”r”);
f2=fopen(“ODD”,”w”);
f3=fopen(“EVEN”,”w”);
while((number=getw(f1))!=EOF)/* Read from data file*/
{
if(number%2==0)
putw(number,f3);/*Write to even file*/
else
putw(number,f2);/*write to odd file*/
}
fclose(f1);
fclose(f2);
fclose(f3);
f2=fopen(“ODD”,”r”);
f3=fopen(“EVEN”,”r”);
printf(“\n\nContents of the odd filen \n”);
while(number=getw(f2))!=EOF)
printf(“%d%d”,number);
printf(“\n\nContents of the even file”);
while(number=getw(f3))!=EOF)
printf(“%d”,number);
fclose(f2);
fclose(f3);
}
The fprintf and fscanf functions:
The fprintf and fscanf functions are identical to printf and scanf functions except that they work on files.
The first argument of these functions is a file pointer which specifies the file to be used.
19
CS3353- C PROGRAMMING AND DATA STRUCTURES UNIT-II C PROGRAMMING –ADVANCED FEATURES
20
CS3353- C PROGRAMMING AND DATA STRUCTURES UNIT-II C PROGRAMMING –ADVANCED FEATURES
} } byte offsets
}
}
}
}
}
100 100 100 100 100 100
bytes bytes bytes bytes bytes bytes
CREATING A RANDOM ACCESS FILE:
Data unformatted (stored as "raw bytes") in random access files.
All data of the same type (ints, for example) use the same memory.
All records of the same type have a fixed length.
Data not human readable.
UNFORMATTED I/O FUNCTIONS:
• fwrite - Transfer bytes from a location in memory to a file
• fread - Transfer bytes from a file to a location in memory
• fwrite( &number, sizeof( int ), 1, myPtr );
– &number - Location to transfer bytes from
– sizeof( int ) - Number of bytes to transfer
– 1 - For arrays, number of elements to transfer
In this case, "one element" of an array is being transferred
– myPtr - File to transfer to or from
– fread similar.
• Writing structs
• fwrite( &myObject, sizeof (struct myStruct), 1, myPtr );
– sizeof - Returns size in bytes of object in parentheses
• To write several array elements
– Pointer to array as first argument
– Number of elements to write as third argument
1. #include<stdio.h>
2. struct clientData
3. {
4. int acctNum;
5. char lastName[15];
6. char firstName[10];
7. double balance;
8. };
9. int main ( )
10. {
11. int i;
12. struct clientData blankClient = {0, "", "", 0.0};
13. FILE *cfPtr;
14. if((cfPtr = fopen("credit.dat","w"))==NULL)
21
CS3353- C PROGRAMMING AND DATA STRUCTURES UNIT-II C PROGRAMMING –ADVANCED FEATURES
22
CS3353- C PROGRAMMING AND DATA STRUCTURES UNIT-II C PROGRAMMING –ADVANCED FEATURES
28. scanf("%d",&client.acctNum);
29. }
30. fclose(cfPtr);
31. }
32. return 0;
33. }
READING DATA SEQUENTIALLY FROM A RANDOM ACCESS FILE:
• fread
– Reads a specified number of bytes from a file into memory.
– fread( &client, sizeof (struct clientData), 1, myPtr );
– Can read several fixed-size array elements
• Provide pointer to array
• Indicate number of elements to read
– To read multiple elements, specify in third argument.
/*Reading Data Sequentially from a Random Access File */
1.#include<stdio.h>
2.struct clientData
3. {
4. int acctNum;
5. char lastName[15];
6. char firstName[10];
7. double balance;
8. };
9.int main( )
10. {
11. int i;
12. struct clientData client = {0, "", "", 0.0};
13. FILE *cfPtr;
14. clrscr();
15. if((cfPtr = fopen("credit.dat","r"))==NULL)
16. printf("File could not be opened");
17. else
18. {
19. printf("%-6s%-16s%-11s%10s\n","Acct","Last Name","First Name", "Balance");
20. while(!feof(cfPtr))
21. {
22. fread(&client,sizeof(struct clientData),1,cfPtr);
23. if(client.acctNum != 0)
24. printf("%6d%16s%11s%10.2f\n",client.acctNum,client.lastName,client.firstName,client.balance);
25. }
26. fclose(cfPtr);
27. }
28. return 0;
29. }
BINARY FILES:
Binary file is a sequence of bytes encoded in binary form for computer storage and processing purposes.
Binary file formats includes text, images, sounds, compressed version of other files, etc.
23
CS3353- C PROGRAMMING AND DATA STRUCTURES UNIT-II C PROGRAMMING –ADVANCED FEATURES
ptr_myfile=fopen("test.bin","wb");
if (!ptr_myfile)
{
printf("Unable to open file!");
return 1;
}
for ( counter=1; counter <= 10; counter++)
24
CS3353- C PROGRAMMING AND DATA STRUCTURES UNIT-II C PROGRAMMING –ADVANCED FEATURES
{
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.
Example:
#include<stdio.h>
/* Our structure */
struct rec
{
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:
25
CS3353- C PROGRAMMING AND DATA STRUCTURES UNIT-II C PROGRAMMING –ADVANCED FEATURES
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.
26