Module5.pptx
Module5.pptx
Introduction to Structures
• Structures (also called structs) are a way to group
related variables into one place. several
•Each variable in the structure is known as a member of the
structure.
•Unlike an array, a structure can many different data
(int, float, char, etc.).
contain
types
•Definition:
Structure is a user-defined data type in C which allows to
combine different data types to store a particular type of
record.
The general format of a structure definition is as
follows:
struct tag_name {
data_type member1;
data_type member2;
–––––––––
–––––––
};
• Consider a book database consisting of book name, author, number of
pages, and price. We can define a structure to hold this information
as follows:
struct book_bank {
char title[20];
char author[15];
int pages;
float price;
};
• The keyword struct declares a structure to hold the details of four data
fields, namely title, author, pages, and price.
• These fields are called structure elements or members.
• Each member may belong to a different type of data
DECLARING STRUCTURE
VARIABLES
• After defining a structure format we can declare variables of that type.
• A structure variable declaration is similar to the declaration
of variables of any other data types.
• It includes the following elements:
1. The keyword struct.
2. The structure tag name.
3. List of variable names separated by commas.
4. A terminating semicolon.
1) Declaring Structure variables separately:
struct book_bank
{
char title[20];
char author[15];
int pages;
float price;
} book1, book2, book3;
Typedef Declarations
• The typedef (derived from type definition) keyword enables the
programmer to create a new data type name from an existing data type.
• By using typedef, new data type is created
• Syntax:
typedef existing data_type new data_type
• Example:
typedef struct student
{
int r_no;
char name[20];
char course[20];
};
main()
{
POINT p1 = {2, 3};
display(p1.x, p1.y);
return 0;
}
Passing a Structure to a Function
• When a structure is passed as an #include<stdio.h>
typedef struct {
argument, it is passed using call by
int x;
value method.
int y;
That is a copy of each member of the }POINT;
structure is made. void display(POINT);
•Syntax: void display( POINT p)
struct struct_name func_name(struct struct_name struct_var);
{
printf("%d %d", p.x, p.y);
}
main() {
POINT p1 = {2, 3};
display(p1);
return 0;
}
Passing Structures through Pointers
• This is more efficient way than call by value method
• When passing a structure to a function by pointer, the
function operates on the original structure, not a copy.
• Inside a function, use the ->tooperator
access structure members
when working with pointers.
WAP using Pointer to Structure to Initialize the Members in the Structure
#include<stdio.h> main()
{
struct student struct student stud1, *ptr_stud1;
{
int r_no; ptr_stud1 = &stud1;
char name[20]; ptr_stud1->r_no = 01;
char strcpy(ptr_stud1->name, "Rahul");
course[20]; strcpy(ptr_stud1->course, "BE");
}; printf("\n DETAILS OF STUDENT");
printf("\n ");
printf("\n ROLL NUMBER = %d", ptr_stud1->r_no);
printf("\n NAME = ", puts(ptr_stud1->name));
printf("\n COURSE = ", puts(ptr_stud1->course));
}
End of Structures topic
Accessing Member of a
Union• A member of a union can be accessed using the same
syntax as that of a structure.
• To access the fields of a union, use the dot operator(.).
• That is the union variable name followed by the
dot operator followed by the member name.
Difference between Structure and Union
Unions inside Structures
Unions inside structures are useful:
• To store multiple types of data, but only one at a time (e.g., int, float,
char).
• To save memory by reusing the same memory location for
different types of data.
• To work with a structure that contains optional or variable data types
(e.g., parsing different formats of data).
#include <stdio.h>
enum days{Sunday=1, Monday, Tuesday,
Wednesday, Thursday, Friday, Saturday};
void main()
{
// printing the values of
weekdays for(int
i=Sunday;i<=Saturday;i++)
{
printf("%d, ",i);
}
}
// C program to create enumerated data type for 7 days. When you provide an enumerator as input to switch
case,
switch(day) {
it should<stdio.h>
#include display like "Today is Monday". case Sunday:
printf("Today is Sunday\n");
enum Day {Sunday=1, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday}; break;
case Monday:
int main() { printf("Today is Monday\n");
break;
case Tuesday:
enum Day day; printf("Today is
int input; Tuesday\n"); break;
case Wednesday:
printf("Enter a number (1 for Sunday, 2 for Monday, ..., "); printf("Today is Wednesday\n");
scanf("%d", &input); break;
case Thursday:
printf("Today is Thursday\n");
if (input < 1 || input > 7) {
break;
printf("Invalid input. Please enter a number between 1 and 7.\n"); case Friday:
return 1; printf("Today is Friday\n");
} break;
case Saturday:
// Assign the input value to the 'day' variable printf("Today is Saturday\n");
day = input; break;
default:
printf("Invalid input\n");
}
return 0;
}
Uses of enum
• Enum are frequently used in switch case statements
• Enums in C are a useful tool for creating more expressive and
maintainable code when you need to represent a fixed set of
values.
• To increase the readability of program instead of directly calling
value name can be used
• When a variable can have only set of values then enum can be used
End of Enumeration (or enum)
Files
Files
• A file is a container in computer storage devices used for storing
data.
Types of Files
•When dealing with files, there are two types of files:
1. Text files
2. Binary files
1. Text files
• Text files are the normal .txt files. It is easy to create text files using
any simple text editors such as Notepad.
• Opening such files, the contents are seen within the file as plain text.
It is easy to edit or delete the contents.
2. Binary files
• Binary files are mostly the .bin files in computers.
• Instead of storing data in plain text, they store it in the binary form
(0's and 1's).
• 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 data from a file,
4. writing data to a file, and
5. closing a file.
Function name Operation
fopen() • Creates a new file for use or Opens an 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 an integer from a file.
putw() • Writes an integer to a file.
• Filename is a string of characters that make up a valid filename for the
operating system. It may contain two parts, a primary name and an
optional period with the extension.
• Examples:
• Student.c
• store
• Text.out
• Data structure of a file is defined as FILE in the library of standard I/O
function definitions.
• Therefore, all files should be declared as type FILE before they are used.
• The FILE type in C is a structure, defined in stdio. h, representing a file
stream. It's an opaque data type, so users interact with it using
pointers, while the library manages its internal details.
1. Creating a new file
• 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;
2. Opening an existing file
• Opening a file is performed using the fopen() function defined in the
stdio.h header file.
• Format :
fptr= fopen(“file open”, “mode”);
Example:
fptr=fopen(“C:\\Desktop\a.txt”, “w”);
• writing as per the mode 'w’.
• Following is the general format for declaring and opening a file:
FILE *fp;
fp = fopen(“p1.c”, “mode”);
• The first statement declares the variable fp as a “pointer to the data
type FILE” and FILE is a structure that is defined in the I/O library.
• The second statement opens the file named p1.c and assigns an
identifier to the FILE type pointer fp.
• This pointer, which contains all the information about the file is
subsequently used as a communication link between the system and the
program.
• The second statement also specifies the purpose of opening this file.
The mode does this job.
Ex: Consider the following statements:
FILE *p1, *p2;
p1 = fopen(“data”, “r”);
p2 = fopen(“results”, “w”);
• The file ‘data’ is opened for reading and file ‘results’ is opened for
writing.
• In case, the results file already exists, its contents are deleted and the
file is opened as a new file.
• If data file does not exist, an error will occur
3. Closing a file
• The file (both text and binary) should be closed after reading/writing.
• This ensures that all outstanding information associated with the file
is flushed out from the buffers and all links to the file are broken.
• Another instance where we have to close a file is when we want to
reopen the same file in a different mode
• Closing a file is performed using the fclose() function.
• fclose(fptr);
• Example:
• The I/O library supports a function to do this for us. It takes the following
form:
fclose(file_pointer);
• This would close the file associated with the FILE pointer file_pointer. Look
at the following segment of a program.
..... .....
FILE *p1, *p2;
p1 = fopen(“a.txt”, “w”);
p2 = fopen(“b.txt”, “r”);
..... .....
fclose(p1);
fclose(p2);
.....
Example: The program opens myfile.txt for reading, reads it line by line into a buffer, and prints
each line to the screen. If the file can't be opened, it will print an error message using perror().
#include <stdio.h>
int main() {
FILE *file = fopen("myfile1.txt", "w");
if (file == NULL)
{
perror("Error opening file");
return 1;
}
int main()
{
FILE *file = fopen("myfile1.txt", "r");
if (file == NULL)
{
perror("Error opening file");
return 1;
}
fprintf(file, "Hello, File!\n");
fputs("Another line.\n", file);
fclose(file);
return 0;
}
// Demo the use of fprintf using " a "
mode
#include <stdio.h>
int main()
{
FILE *file = fopen("myfile.txt", "a"); // Open for appending
if (file == NULL) {
perror("Error opening file");
return 1;
}
int main() {
FILE *file = fopen("myfile1.txt", "r");
if (file == NULL)
{
perror("Error opening file for reading");
return 1;
}
char name[50];
fscanf(file, "%s", name);
printf("Name read from file: %s\n", name);
fclose(file);
return 0;
}
getc and putc Functions
• The simplest file I/O functions are getc and putc.
• These are analogous to getchar and putchar functions and handle one
character at a time.
• Assume that a file is opened with mode ‘w’ and file
pointerfp1. Then, the statement :
putc(c, fp1);
• This writes the character contained in the character variable c to the
file associated with FILE pointer fp1.
• Similarly, getc is used to read a character from a file that has been
opened in read mode.
• For example, the statement
c = getc(fp2);
• would read a character from the file whose file pointer is fp2.
• The file pointer moves by one character position for every operation of
getc or putc.
• The getc will return an end-of-file marker EOF, when end
of the file has been reached.
• Therefore, the reading should be terminated when EOF is encountered.
// Demo the use of getc and
#include
putc
<stdio.h> void
main() {
FILE *f1;
char c;
printf("Data Input:\n\n");
f1 = fopen("input.txt", "w");
while((c=getchar()) != EOF)
putc(c,f1);
fclose(f1);
printf("\nData
Output:\n\n"); f1 =
fopen("input.txt","r");
while((c=getc(f1)) !=
EOF) printf("%c",c);
getw and putw Functions
• The getw and putw are integer-oriented functions.
• They are used to read and write integer values.
• These functions would be useful when using only integer data.
• The general forms of getw and putw are as follows:
putw(integer, fp);
getw(fp);
// Demo the use of getw and f1 = fopen("number.txt", "r");
putw
#include <stdio.h> if (f1 == NULL) {
int main() { perror("Error opening file for reading");
FILE *f1; int num; return 1;
}
f1 = fopen("number.txt", "w");
num = getw(f1);
if (f1 == NULL) {
if (num == EOF) {
perror("Error opening file for writing");
perror("Error reading integer from file");
return 1; fclose(f1);
} return 1;
}
printf("Enter a number to write to the file: ");
scanf("%d", &num); printf("The number read from the file is: %d\n", num)
putw(num, f1); fclose(f1);
fclose(f1); return 0;
}
Detecting the End of File
• The function feof() is used to check the end of file after EOF.
• It tests the end of file indicator. It returns non-zero value if successful
otherwise, zero.
// A simple program that demonstrates the use of feof()