0% found this document useful (0 votes)
4 views34 pages

Module 5

Module 5 covers structures, unions, and file handling in C programming. It explains how to define and use structures and unions, including accessing members, copying, and comparing structures, as well as the use of typedef and nested structures. Additionally, it details file operations such as opening, reading, writing, and closing files, along with standard input/output functions.
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)
4 views34 pages

Module 5

Module 5 covers structures, unions, and file handling in C programming. It explains how to define and use structures and unions, including accessing members, copying, and comparing structures, as well as the use of typedef and nested structures. Additionally, it details file operations such as opening, reading, writing, and closing files, along with standard input/output functions.
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
You are on page 1/ 34

MODULE 5

Structures, unions & files


Introduction: ( structure)
◦ A structure is a user defined data type that can store related information of different data types).
◦ It is similar to records and can be used to store information about an entity.
◦ The major difference between structure and an array is that array contains related information of the same data
type
◦ structure therefore is a collection of variables of different data types under a single name.
◦ The variables within a structure are of different data types and each has a name that is used to select it from the structure.
Structure declaration:
◦ A structure is defined by the keyword struct followed by the structure name.
struct student
{
int usn;
char name[20];
char course[20];
float fees;
};
◦ In the above example usn, name, course, fees are the members of structure student
◦ Structure is a user defined data type.
◦ Size of structure is the addition of all size of all members. It will be equal to sum of all members or more.
◦ Each variable name declared within a structure is called a member of the structure.
◦ The structure declaration, however does not allocate any memory or consume storage space. It just gives a template that
conveys to C compiler how the structure could be laid out in the memory and give details of the member names.
◦ Memory will be allotted only after we create a variable of type structure
◦ Structures can be local or global.
creating variable of structure data type:
struct student stud1;
Creating structure variable and assigning values:
struct student
{
int usn;
char name[20];
char course[20];
float fees;
} stud1, stud2;

struct student
{
int usn;
char name[20];
char course[20]; or struct student stud1= {01,”Rahul”, “BCA”, 45,000};
float fees;
} stud1={01,Rahul, “BCA”, 45,000};
Accessing the members of the structure:
◦ A structure member variable is generally accessed through the dot operator.
struct student stud1,stud2;

scanf(“%d”,&stud1.rno);
scanf(“%s”,&stud1.name);
printf(“%d”, stud1.rno);

Copying structures:
struct student stud1={01,”Rahul”,”BCA”,45000};
stud2=stud1;
Comparing structures:
◦ C does not permit comparison of one structure to another. But, individual variables can be compared.
if(stud1.fees > stud2.fees)  valid statement.
Array of structures:
typedef declaration:
◦ typedef keyword enables the programmer to create a new data type name from an existing data type.
◦ By using typedef no new data is created rather an alternate name(alias) is given to a known data type.
typedef int INTEGER
INTEGER num=5;

student stud1;
Nested structure :
One of he structure members will be in turn another
structure

struct student stud1;


To read roll_no:
scanf(“%d”,&stud1.roll_no);

To read DOB:
scanf(“%d %d %d”, &stud1.date.day, &stud1.date.month,
&stud1.date.year);
Passing individual members: Passing entire structure:
Unions:
◦ Similar to structures, a union is a collection of variables of different data types
◦ the only difference between structure and union is that in case of unions you can only store information in
one field at anyone time.
Unions inside structure:
Enumerated data type:
◦ Enumerated data type is a user defined type based on the standard integer type.
◦ Enumeration consists of a set of named integer constants. (each integer is assigned an identifier)
◦ The identifier can be used as a symbolic name to make the program more readable. enum is the keyword.
enum COLORS { red, blue, black, green, yellow, purple, white}; COLORS is the new data type
In the above example red=0, blue=1, black =2 and so on…
enum COLORS { red=2, blue, black=5, green=7, yellow, purple, white};
enum COLORS { red, blue, black, green, yellow, purple, white};
enum COLORS c; or int c;
c= black+white
or
c= enum COLORS(black+white) // valid
or
We should declare c as integer.
Files:
◦ File is a collection of data stored on a secondary storage device like hard disk,USB etc.
◦ When there is a huge amount of data taking the input from the computer's keyboard will be a tedious job.
◦ A better solution therefore is to combine all input data into file and then design a C program to read this data
from the file whenever required.

Reasons for reading from files:


1. It becomes cumbersome and time consuming to handle huge amount of data through terminals
2. when doing input output using terminal the entire data is lost when the program is terminated or computer
is turned off.

Standard streams in C
stdin
stdout
Stderr (errno.h, perror())
Using Files in C:
To use files in C, we must follow the steps even below:
1. declare file pointer variable
2. open the file
3. process to file
4. close the file

Declaring the file pointer variable:


◦ we must specify the name of the file that has to be used this is accomplished by using a file
pointer variable what points to a structure FILE. (stdio.h)
FILE *file_pointer_name;
FILE *fp;
The fp is the file pointer.
Opening a file:
◦ A file must be first opened before data can be read
from it or written to it.
◦ In order to open a file and associate with the stream,
the fopen() function is used.
FILE *fopen(const char *file_name, const char
*mode);
◦ A pointer to structure is returned if it is successful
◦ if it fails it returns null.
fopen() might fail in the following cases:
◦ Opening a file that is not ready for use.
◦ opening the file that is specified to be on non existent directory or drive.
◦ opening a non existent file for reading.
◦ opening a file to which access is not permitted.

Closing a file using fclose()


int fclose( FILE *fp);  fclose(fp);
◦ All the buffer or unprocessed input will be flushed
◦ fcloseall();
Reading data from files:
1) fscanf()
2) fgets()
3) fgetc()
4) fread()
Reading data from files:
◦ fscanf()
fscanf(FILE *stream, const char *format, …);
fgets()
char *fgets( char *str,int size, FILE *stream); // only reads string.
◦ Reads at most one less than the number of characters specified by size from the given stream and stores in the string str.
◦ The function terminates as soon as it encounters either a null Character or EOF or specified numbers or any other error.
fgetc():
◦ Returns the next character from the stream.
◦ EOF if the end of file is reached.
Example:
fp= fopen(“program.c” ,”r”);
ch=fgetc(fp); // most of the times put in a loop.
fread()
int fread(void *str, ;size_t size, size_t num, FILE *stream);
◦ Upon successful reading it will return number of
bytes read.

fp=fopen(“letter,txt”, “r+”);
fread(str, 1, 10,fp);
1 byte (units) in one read.
Total 10 bytes
fread(str, 3, 10,fp);
Size of each element to read = 3 bytes
Number of such elements to read = 10 blocks
Total of 30 bytes would be read.
Writing data to files:
1. fprintf()
int fprint(FILE *stream, const char *format,…);
Example:
fp=fopen(“details.TXT”, w);
….
fprintf(fp, “%d Name: %s, Salary: %f”, i, name, salary);

2. fputs() – used to write a line to a file


int fputs(const char *str, FILE *stream);
Example:
fp=fopen(“comments.TXT”, w);

gets(feedback); // input to feedback.
fputs(feedback, fp); //the given input feedback will be written to comments.TXT
fputc()
◦ Used to write a character to the stream one by one.
◦ fputc(str[i],fp);

fwrite()
int fwrite(const void *str, size_t size, size_t count, FILE *stream);
fwrite() can be used to write characters ,integers to a file.
fwrite(str,1,12,fp);
Detecting End Of file:
◦ When reading or writing data to files we often don't know exactly how long the file is.
◦ In C there are 2 ways to detect the end of file.
1. While reading the file in text mode character by character the program can compare the character that has
been read with EOF, which is symbolic constant defined in stdio.h with the value of -1.

2.Other way is to use standard library function feof() which is defined in stdio.h. This function takes a pointer
to the file structure to check as an argument and returns zero when the end of file has not reached and a
one if end of file is reached.
◦ALL THE BEST

You might also like