0% found this document useful (0 votes)
2 views19 pages

Understanding Structures in C Programming

The document provides a comprehensive overview of structures in C, detailing their definition, usage, and examples, including how to define structures, pass them to functions, and create arrays of structures. It also covers self-referential structures, typedef, unions, and file management operations in C, explaining how to create, open, read, and write files. Additionally, it discusses the differences between text and binary files and the importance of closing files after operations.

Uploaded by

MALARMANNAN A
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views19 pages

Understanding Structures in C Programming

The document provides a comprehensive overview of structures in C, detailing their definition, usage, and examples, including how to define structures, pass them to functions, and create arrays of structures. It also covers self-referential structures, typedef, unions, and file management operations in C, explaining how to create, open, read, and write files. Additionally, it discusses the differences between text and binary files and the importance of closing files after operations.

Uploaded by

MALARMANNAN A
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

C Structure

Structure in c is a user-defined data type that enables us to store the collection of different data types. Each
element of a structure is called a member. Structures ca; simulate the use of classes and templates as it can
store various information. The ,struct keyword is used to define the structure.

A structure is a user defined data type in C. A structure creates a data type that can be used to group
items of possibly different types into a single type.

In C programming, a struct (or structure) is a collection of variables (can be of different types) under a
single name.

How to define structures?


Before you can create structure variables, you need to define its data type. To define a struct,
the struct keyword is used.

Syntax of struct
struct structureName

dataType member1;

dataType member2;

...

};

Example:
struct Person

char name[50];

int citNo;

float salary;

};
Here, struct is the keyword; employee is the name of the structure; id, name, and salary are the members or fields
of the structure.

Example:
#include<stdio.h>

#include <string.h>

struct employee

{ int id;

char name[50];

}e1; //declaring e1 variable for structure

int main( )

//store first employee information

[Link]=101;

strcpy([Link], "Kumararaja");//copying string into char array

//printing first employee information

printf( "Employee 1 id : %d\n", [Link]);

printf( "Employee 1 name : %s\n", [Link]);


return 0;

Output:

Employee 1 id : 101

Employee 1 name : Kumararaja

Structures and Functions


A structure information can be passed as a function arguments. The structure variable may be passed as a
value or reference. The function will return the value by using the return statement.

Program

#include <stdio.h>
int add(int, int) ; //function declaration
int main()
{
//structures declartion
struct addition{
int a, b;
int c;
}sum;
printf("Enter the value of a : ");
scanf("%d",&sum.a);
printf("\nEnter the value of b : ");
scanf("%d",&sum.b);
sum.c = add(sum. a, sum.b); //passing structure members as arguments to function
printf("\nThe sum of two value are : ");
printf("%d ", sum.c);
return 0;
}
//Function definition
int add(int x, int y)
{
int sum1;
sum1 = x + y;
return(sum1);
}
Output:
Enter the value of a : 10
Enter the value of b: 20
The sum of two value are : 30

Array of Structures
As you know, C Structure is collection of different datatypes ( variables ) which are grouped together.
Whereas, array of structures is nothing but collection of structures. This is also called as structure array in
C.

EXAMPLE PROGRAM FOR ARRAY OF STRUCTURES IN C:

This program is used to store and access “id, name and percentage” for 3 students. Structure array is used
in this program to store and display records for many students. You can store “n” number of students
record by declaring structure variable as ‘struct student record[n]“,

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

struct student
{
int id;
char name[30];
float percentage;
};

int main()
{
int i;
struct student record[3];

// 1st student's record


record[0].id=1;
strcpy(record[0].name, "Raja");
record[0].percentage = 86.5;

// 2nd student's record


record[1].id=2;
strcpy(record[1].name, "Nithish");
record[1].percentage = 90.5;

// 3rd student's record


record[2].id=3;
strcpy(record[2].name, "Sai");
record[2].percentage = 81.5;
for(i=0; i<3; i++)
{
printf(" Records of STUDENT : %d \n", i+1);
printf(" Id is: %d \n", record[i].id);
printf(" Name is: %s \n", record[i].name);
printf(" Percentage is: %f\n\n",record[i].percentage);
}
return 0;
}

Output:
Records of STUDENT : 1
Id is: 1
Name is: Raja
Percentage is: 86.500000

Records of STUDENT : 2
Id is: 2
Name is: Nithish
Percentage is: 90.500000

Records of STUDENT : 3
Id is: 3
Name is: Sai
Percentage is: 81.500000

Structure using Pointer


C structure can be accessed in 2 ways in a C program. They are,
1. Using normal structure variable
2. Using pointer variable
Dot(.) operator is used to access the data using normal structure variable and arrow (->) is used to access
the data using pointer variable.

EXAMPLE PROGRAM FOR C STRUCTURE USING POINTER:

In this program, “record1” is normal structure variable and “ptr” is pointer structure variable. As you know,
Dot(.) operator is used to access the data using normal structure variable and arrow(->) is used to access
data using pointer variable.

#include <stdio.h>
#include <string.h>
struct student
{
int id;
char name[30];
float percentage;
};

int main()
{
int i;
struct student record1 = {1, "Raju", 90.5};
struct student *ptr;

ptr = &record1;

printf("Records of STUDENT1: \n");


printf(" Id is: %d \n", ptr->id);
printf(" Name is: %s \n", ptr->name);
printf(" Percentage is: %f \n\n", ptr->percentage);

return 0;
}
Output
Records of STUDENT1:
Id is: 1
Name is: Raju
Percentage is: 90.500000

Self Referential Structures


Structures pointing to the same type of structures are self-referential in nature. Self referential structures are a
structure that refers to itself.
Example:1
struct node
{
int data1;
char data2;
struct node* link;
};
int main()
{
struct node ob;
return 0;
}
„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.

Example :2
Struct node
{
Int data;
Struct node* next;
};

Definition
It is a data structure in which the pointer refers(points) to the structure of the same type. The data
structure like Linked list, trees, graphs and heap etc.,
C Typedef
In C, the typedef(keyword) allows the programmers to define the new data type name by using existing
data types in C. The existing data types are int, char, float, arrays, structures and so on. There is no new
data type is produced, rather than a new data type name is created. Once a new data type name is created,
then variables, structures, arrays can be declared and initialized in terms of the new data type name. The
keyword typedef helps to increase the clarity in C programs.


Variable for the above structure can be declared in two ways.
st
1 way :

struct student record; /* for normal variable */


struct student *record; /* for pointer variable */

2nd way :
typedef struct student status;

Program

#include <stdio.h>
int main()
{
typedef int kumar; //creating new data type name rectangle using typedef
kumar length, breadth, area; //declaring variables using new data type name rectangle
printf("\nEnter length of the rectangle ");
scanf("%d", &length);
printf("\nEnter breath of the rectangle ");
scanf("%d",&breadth);
area = length * breadth;
printf("\nArea = %d ", area);
return 0;
}
Output:
Enter length of the rectangle 5
Enter breath of the rectangle 2
Area = 10
TABLE LOOK UP
Table-lookup package, to illustrate more aspects of structures. This code is typical of what might be found
in the symbol table management routines of a macro processor or a compiler. For example, consider
the #define statement. When a line like
#define IN 1
is encountered, the name IN and the replacement text 1 are stored in a table. Later, when the
name IN appears in a statement like
state = IN;
it must be replaced by 1.
There are two routines that manipulate the names and replacement texts. install(s,t) records the name sand
the replacement text t in a table; s and t are just character strings. lookup(s) searches for s in the table, and
returns a pointer to the place where it was found, or NULL if it wasn't there.
The algorithm is a hash-search - the incoming name is converted into a small non-negative integer, which
is then used to index into an array of pointers. An array element points to the beginning of a linked list of
blocks describing names that have that hash value. It is NULL if no names have hashed to that value.
A block in the list is a structure containing pointers to the name, the replacement text, and the next block in
the list. A null next-pointer marks the end of the list.
struct nlist { /* table entry: */
struct nlist *next; /* next entry in chain */
char *name; /* defined name */
char *defn; /* replacement text */
};
BIT FIELDS
In C, we can specify size (in bits) of structure and union members. The idea is to use memory efficiently
when we know that the value of a field or group of fields will never exceed a limit or is withing a small
range.
For example, consider the following declaration of date without use of bit fields.
#include <stdio.h>

// A simple representation of date


struct date
{
int d;
int m;
int y;
};

int main()
{
printf("Size of date is %d bytes\n", sizeof(struct date));
struct date dt = {31, 12, 2014};
printf("Date is %d/%d/%d", dt.d, dt.m, dt.y);
}
Output:
Size of date is 12 bytes
Date is 31/12/2014
C Union
Like structure, Union in c language is a user-defined data type that is used to store the different type of
elements.

At once, only one member of the union can occupy the memory. In other words, we can say that the size of the
union in any instance is equal to the size of its largest element.

Advantage of union over structure

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

Defining union
The union keyword is used to define the union. Let's see the syntax to define union in c.

union union_name
{
data_type member1;
data_type member2;
.
.
data_type memeberN;
};

Let's see the example to define union for an employee in c.


union employee
{ int id;
char name[50];
float salary;
};
C Union example
Let's see a simple example of union in C language.

#include <stdio.h>
#include <string.h>
union employee
{ int id;
char name[50];
}e1; //declaring e1 variable for union
int main( )
{
//store first employee information
[Link]=101;
strcpy([Link], "Kumar");//copying string into char array
//printing first employee information
printf( "employee 1 id : %d\n", [Link]);
printf( "employee 1 name : %s\n", [Link]);
return 0;
}

Output:

employee 1 id : 1869508435
employee 1 name : Kumar

C File management
A File can be used to store a large volume of persistent data. Like many other languages 'C' provides
following file management functions,
1. Creation of a file
2. Opening a file
3. Reading a file
4. Writing to a file
5. Closing a file

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. Creation of a new file (fopen with attributes as “a” or “a+” or “w” or “w++”)
2. Opening an existing file (fopen)
3. Reading from file (fscanf or fgets)
4. Writing to a file (fprintf or fputs)
5. Moving to a specific location in a file (fseek, rewind)
6. Closing a file (fclose)

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 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\\[Link]","w");
fopen("E:\\cprogram\\[Link]","rb");

 Let's suppose the file [Link] doesn't exist in the location E:\cprogram. The first function
creates a new file named [Link] 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 [Link] 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.
C Opening Modes of Files

Mode Meaning Description

w Write Create a file for writing, if the file already exist, it will be used to
overwrite a file.

r Read Opening a file for reading only

a Append Opening a file to writing at an end of file.

w+ Write + Read Opening a file for writing and reading

r+ Read + Write Opening a file for reading and writing

a+ Append + Opening a file to update or append information


Read

How to Create a File

Syntax:
FILE *fp;
fp = fopen ("file_name", "mode");

#include <stdio.h>
int main() {
FILE *fp;
fp = fopen ("[Link]", "w");
}

Example Program for File Open


#include <stdio.h>
int main() {
FILE *fptr;
fptr = fopen("[Link]", "w"); // "w" defines "writing mode"
/* write to file */
fprintf(fptr, "Welcome C Language\n");
fputs("We don't need to use for loop\n", fptr);
fclose(fptr);
return 0; }
Example2

#include <stdio.h>
int main()
{
FILE *fptr; //File pointer declaration
char name[40];
int age;
fptr = fopen("[Link]", "w+ "); //the function fopen opens the record text file
printf("\nEnter your name : ");
scanf("%s", name);
printf("\nEnter your age : ");
scanf("%d",&age);
fprintf(fptr,"%s\n", name); //the entered name is written in to the file
fprintf(fptr,"%d\n ", age); //the entered age is written to the file
fclose(fptr); //the function closes the opened file
return 0;
}
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.

Following are the most important file management functions available in 'C,'

function purpose

fopen () Creating a file or opening an existing file

fclose () Closing a file

fprintf () Writing a block of data to a file

fscanf () Reading a block data from a file

getc () Reads a single character from a file

putc () Writes a single character to a file

getw () Reads an integer from a file


putw () Writing an integer to a file

Sets the position of a file pointer to a specified


fseek ()
location

ftell () Returns the current position of a file pointer

rewind () Sets the file pointer at the beginning of a file

Read the File


#include <stdio.h>
#include <stdlib.h> // For exit()
int main()
{
FILE *fptr;

char filename[100], c;

printf("Enter the filename to open \n");


scanf("%s", filename);

// Open file
fptr = fopen(filename, "r");
if (fptr == NULL)
{
printf("Cannot open file \n");
exit(0);
}

// Read contents from file


c = fgetc(fptr);
while (c != EOF)
{
printf ("%c", c);
c = fgetc(fptr);
}
fclose(fptr);
return 0;
}

Rename the file


#include <stdio.h>
int main()
{
// Path to old and new files
char oldName[100], newName[100];
// Input old and new file name
printf("Enter old file path: ");
scanf("%s", oldName);

printf("Enter new file path: ");


scanf("%s", newName);

// rename old file with new name


if (rename(oldName, newName) == 0)
{
printf("File renamed successfully.\n");
}
else
{
printf("Unable to rename files.\n");
}
return 0;
}
Read and Write mode
#include <stdio.h>
int main()
{
FILE *fptr; //File pointer declaration

char name[40], name1[40];


fptr=fopen("[Link]","w");
fptr = fopen("[Link]", "r+");

//the function fopen opens the record text file


printf("\nEnter your name : ");
scanf("%s", name);

fputs(name,fptr); //the entered name is written in to the file

rewind(fptr); //returns pointer to the starting point of the file

fscanf(fptr, "%s ", name1); //reads the name from file

printf("Name reads from File : %s", name1);


fclose(fptr); //the function closes the opened file
return 0;
}

File Append example


#include <stdio.h>
int main()
{
FILE *fptr; //File pointer declaration
char ch;
fptr = fopen("[Link]", "a "); //the function fopen opens the record text file
printf("\nEnter characters with a space to write into a file press 'y 'to stop writing : ");
scanf("%c",&ch);
while(ch != 'y')
{
fputc(ch, fptr);
scanf("%c",&ch);
}
fclose(fptr); //the function closes the opened file
return 0;
}

Error Handling in C

C language does not provide any direct support for error handling. However a few methods and variables
defined in error.h header file can be used to point out error using the return statement in a function. In C
language, a function returns -1 or NULL value in case of any error and a global variable errno is set with
the error code. So the return value can be used to check error while programming.

What is errno?

Whenever a function call is made in C language, a variable named errno is associated with it. It is a global
variable, which can be used to identify which type of error was encountered while function execution,
based on its value. Below we have the list of Error numbers and what does they mean.

errno value Error

1 Operation not permitted

2 No such file or directory

3 No such process

4 Interrupted system call

5 I/O error

6 No such device or address

7 Argument list too long


8 Exec format error

9 Bad file number

10 No child processes

11 Try again

12 Out of memory

13 Permission denied

C language uses the following functions to represent error messages associated with errno:
 perror(): returns the string passed to it along with the textual represention of the current errno value.
 strerror() is defined in string.h library. This method returns a pointer to the string representation of
the current errno value.

Example program error handling


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

int main ()
{
FILE *fp;
/*
If a file, which does not exists, is opened,
we will get an error
*/
fp = fopen("[Link]", "r");
printf("Value of errno: %d\n ", errno);
printf("The error message is : %s\n", strerror(errno));
perror("Message from perror");

return 0;
}

Output
Value of errno: 2
The error message is : No such file or directory
Message from perror: No such file or directory
Miscellaneous functions

Miscellaneous functions perform a variety of operations and return specific information or values.
C environment functions such as getenv(), setenv(), putenv() and other functions perror(), random() and
delay() are given below.

Miscellaneous functions Description

getenv() This function gets the current value of the environment variable

setenv() This function sets the value for environment variable

putenv() This function modifies the value for environment variable

Displays most recent error that happened during library function


perror()
call

rand() Returns random integer number range from 0 to at least 32767

delay() Suspends the execution of the program for particular time

EXAMPLE PROGRAM FOR GETENV() FUNCTION IN C:

 This function gets the current value of the environment variable.

 Let us assume that environment variable DIR is assigned to “/usr/bin/test/”. Below program will
show you how to get this value using getenv() function.

#include <stdio.h>
#include <stdlib.h>

int main()
{
printf("Directory = %s\n", getenv("DIR"));
return 0;
}

You might also like