Module5-PPT & Notes(Structure & Files) (1)
Module5-PPT & Notes(Structure & Files) (1)
CHAPTER 15
STRUCTURES
1. Structured Declaration
2. Typedef Declarations
3. Initialization of Structures
4. Accessing the members of a structure
5. Copying and comparing structures
6. Finding the size of a structure – simple addition, using
sizeof operator, subtracting the addresses
●stud1.DOB.mm = 09;
●stud1.DOB.yy = 1990;
●stud1.fees = 45000;
© Oxford University Press 2012. All rights reserved.
Write a program to read and display information of a student using
● #include<stdio.h> structure within a structure
● int main()
● { struct DOB
● {
● int day;
● int month;
● int year;
● };
● struct student
● { int roll_no;
● char name[100];
● float fees;
● struct DOB date;
● };
● struct student stud1;
● printf(“\n Enter the roll number : “);
● scanf(“%d”, &stud1.roll_no);
● printf(“\n Enter the name : “);
● scanf(“%s”, stud1.name);
● printf(“\n Enter the fees : “);
● scanf(“%f”, &stud1.fees);
● printf(“\n Enter the DOB : “);
● scanf(“%d %d %d”, &stud1.date.day, &stud1.date.month, &stud1.date.year);
● printf(“\n ********STUDENT’S DETAILS *******”);
● printf(“\n ROLL No. = %d”, stud1.roll_no);
● printf(“\n NAME. = %s”, stud1.name);
● printf(“\n FEES. = %f”, stud1.fees);
● printf(“\n DOB = %d - %d - %d”, stud1.date.day, stud1.date.month, stud1.date.year);
● }
● The general syntax for declaring an array of structure can be given as,
● struct struct_name struct_var[index];
● struct student stud[30];
● Now, to assign values to the ith student of the class, we will write,
● stud[i].r_no = 09;
● stud[i].name = “RASHI”;
● stud[i].course = “MCA”;
● stud[i].fees = 60000;
● #include<stdio.h>
● typedef struct
● {
● int x;
● int y;
● }POINT;
● void display(int, int);
● main()
● {
● POINT p1 = {2, 3};
● display(p1.x, p1.y);
● return 0;
● }
● void display( int a, int b)
● {
● printf("%d %d", a, b);
● }
© Oxford University Press 2012. All rights reserved.
PASSING A STRUCTURE TO A FUNCTION
● When a structure is passed as an argument, it is passed using call by value method. That is a
copy of each member of the structure is made. No doubt, this is a very inefficient method
especially when the structure is very big or the function is called frequently. Therefore, in such a
situation passing and working with pointers may be more efficient.
● The general syntax for passing a structure to a function and returning a structure can be given
as, struct struct_name func_name(struct struct_name struct_var);
● The code given below passes a structure to the function using call-by-value method.
● #include<stdio.h>
● typedef struct
● {
● int x;
● int y;
● }POINT;
● void display(POINT);
● main()
● {
● POINT p1 = {2, 3};
● display(p1);
● return 0;
● }
● void display( POINT p)
● {
● printf("%d %d", p.x, p.y);
● }
● Self referential structures are those structures that contain a reference to data of its same type.
That is, a self referential structure in addition to other data contains a pointer to a data that is of
the same type as that of the structure. For example, consider the structure node given below.
● struct node
● {
● int val;
● struct node *next;
● };
● Here the structure node will contain two types of data- an integer val and next that is a pointer
to a node. You must be wondering why do we need such a structure? Actually, self-referential
structure is the foundation of other data structures.
● Enumerated types can be implicitly or explicitly cast. For ex, 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 warning message.
● To understand this, answer one question. If we write:
● enum COLORS{RED, BLUE, BLACK, GREEN, YELLOW, PURPLE, WHITE};
● enum COLORS c;c = BLACK + WHITE;
● Here, c is an enumerate data type variable. If we write, c = BLACK + WHITE, then logically, it
should be 2 + 6 = 8; which is basically a value of type int. However, the left hand side of the
assignment operator is of the type enum COLORS. SO the statement would complain an error.
● 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. :
● c = enum COLORS(BLACK + WHITE);
FILE HANDLING IN C
STREAMS IN C
● In C, the standard streams are termed as pre-connected input and output channels between a
text terminal and the program (when it begins execution). Therefore, stream is a logical
interface to the devices that are connected to the computer.
● Stream is widely used as a logical interface to a file where a file can refer to a disk file, the
computer screen, keyboard, etc. Although files may differ in the form and capabilities, all
streams are the same.
● The three standard streams in C languages are- standard input (stdin), standard output (stdout)
and standard error (stderr).
● Standard input (stdin): Standard input is the stream from which the
program receives its data. The program requests transfer of data using
the read operation. However, not all programs require input. Generally,
unless redirected, input for a program is expected from the keyboard.
KEYBOARD
● Standard output (stdout): Standard output is the stream where a
stdin
program writes its output data. The program requests data transfer
PROGRAM
using the write operation. However, not all programs generate output.
stderr
● Standard error (stderr): Standard error is basically an output stream
used by programs to report error messages or diagnostics. It is a SCREEN
separately. No doubt, the standard output and standard error can also
be directed to the same destination.
● A stream is linked to a file using an open operation and disassociated
from a file using a close operation.
Similarly, when reading data from a disk file, the data is read as a block from the file and written
into the buffer. The program reads data from the buffer. The creation and operation of the buffer is
automatically handled by the operating system. However, C provides some functions for buffer
manipulation. The data resides in the buffer until the buffer is flushed or written to a file.
© Oxford University Press 2012. All rights reserved.
TYPES OF FILES
● In C, the types of files used can be broadly classified into two categories- ASCII text files
and binary files.
1. ASCII Text files
● A text file is a stream of characters that can be sequentially processed by a computer in forward
direction. For this reason a text file is usually opened for only one kind of operation (reading,
writing, or appending) at any given time.
● Because text files only process characters, they can only read or write data one character at a
time.
● In a text file, each line contains zero or more characters and ends with one or more characters
that specify the end of line. Each line in a text file can have maximum of 255 characters.
● A line in a text file is not a c string, so it is not terminated by a null character. When data is
written to a text file, each newline character is converted to a carriage return/line feed character.
Similarly, when data is read from a text file, each carriage return/ line feed character is
converted in to newline character.
● Another important thing is that when a text file is used, there are actually two representations of
data- internal or external. For ex, an int value will be represented as 2 or 4 bytes of memory
internally but externally the int value will be represented as a string of characters representing
its decimal or hexadecimal value. To convert internal representation into external, we can use
printf and fprintf functions. Similarly, to convert an external representation into internal scanf
© Oxford University Press 2012. All rights reserved.
and fscanf can be used.
2. BINARY FILES
● A binary file is a file which may contain any type of data, encoded in binary form for computer
storage and processing purposes. Like a text file, a binary file is a collection of bytes. Note that
in C a byte and a character are equivalent. Therefore, a binary file is also referred to as a
character stream with following two essential differences.
● A binary file does not require any special processing of the data and each byte of data is
transferred to or from the disk unprocessed.
● C places no constructs on the file, and it may be read from, or written to, in any manner the
programmer wants.
● Binary files store data in the internal representation format. Therefore, an int value will be stored
I binary form as 2 or byte value. The same format is used to store data in memory as well as in
file. Like text file, binary file also ends with an EOF marker.
● Binary files can be either processed sequentially or randomly.
● In a text file, an integer value 123 will be stored as a sequence of three characters- 1, 2 and 3.
So each character will take 1 byte and therefore, to store the integer value 123 we need 3
bytes. However, in a binary file, the int value 123 will be stored in 2 bytes in the binary form.
This clearly indicates that binary files takes less space to store the same piece of data and
eliminates conversion between internal and external representations and are thus more efficient
than the text files.
© Oxford University Press 2012. All rights reserved.
USING FILES IN C
MODE DESCRIPTION
r Open a text file for reading. If the stream (file) does not exist then an error will be reported.
Open a text file for writing. If the stream does not exist then it is created otherwise if the file already exists, then its
w
contents would be deleted
a Append to a text file. if the file does not exist, it is created.
rb Open a binary file for reading. B indicates binary. By default this will be a sequential file in Media 4 format
wb Open a binary file for writing
ab Append to a binary file
Open a text file for both reading and writing. The stream will be positioned at the beginning of the file. When you
r+
specify "r+", you indicate that you want to read the file before you write to it. Thus the file must already exist.
Open a text file for both reading and writing. The stream will be created if it does not exist, and will be truncated if it
w+
exist.
a+ Open a text file for both reading and writing. The stream will be positioned at the end of the file content.
r+b/ rb+ Open a binary file for read/write
w+b/wb+ Create a binary file©
forOxford University Press 2012. All rights reserved.
read/write
a+b/ab+ Append a binary file for read/write
OPENINING A FILE contd.
● The fopen() can fail to open the specified file under certain conditions that are listed below:
● Opening a file that is not ready for usage
● Opening a file that is specified to be on a non-existent directory/drive
● Opening a non-existent file for reading
● Opening a file to which access is not permitted
FILE *fp;
● fp = fopen("Student.DAT", "r");
● if(fp==NULL)
● {
● printf("\n The file could not be opened");
● exit(1);
● }
● OR
● char filename[30];
● FILE *fp;
● gets(filename);
● fp = fopen(filename, "r+");
● if(fp==NULL)
● {
● printf("\n The file could not be opened");
● exit(1);
● }
● To close an open file, the fclose() function is used which disconnects a file pointer from a file.
After the fclose() has disconnected the file pointer from the file, the pointer can be used to
access a different file or the same file but in a different mode.
● The fclose() function not only closes the file but also flushed all the buffers that are maintained
for that file
● If you do not close a file after using it, the system closes it automatically when the program
exits. However, since there is a limit on the number of files which can be open simultaneously;
the programmer must close a file when it has been used. The prototype of the fclose() function
can be given as,
● int fclose(FILE *fp);
● Here, fp is a file pointer which points to the file that has to be closed. The function returns an
integer value which indicates whether the fclose() was successful or not. A zero is returned if
the function was successful; and a non-zero value is returned if an error occurred.
fscanf()
The fscanf() is used to read formatted data from the stream. The syntax of the fscanf() can be
given as,
● int fscanf(FILE *stream, const char *format,…);
● The fscanf() is used to read data from the stream and store them according to the parameter
format into the locations pointed by the additional arguments.
● #include<stdio.h>
● main()
● { FILE *fp;
char name[80];
int roll_no;
fp = fopen("Student.DAT", "r");
if(fp==NULL)
{ printf("\n The file could not be opened");
● exit(1);
}
printf("\n Enter the name and roll number of the student : ");
fscanf(stdin, "%s %d", name, &roll_no); /* read from keyboard */
printf(“\n NAME : %s \t ROLL NUMBER = %d", name, roll_no);
// READ FROM FILE- Student.DAT
fscanf(fp, "%s %d", name, &roll_no);
printf(“\n NAME : © %sOxford University
\t ROLL NUMBER Press 2012.
= %d", All rights
name, reserved.
roll_no);
fclose(fp);
fgets()
● fgets() stands for file get string. The fgets() function is used to get a string from a stream. The
syntax of fgets() can be given as:
● char *fgets(char *str, int size, FILE *stream);
● The fgets() function reads at most one less than the number of characters specified by size
(gets size - 1 characters) from the given stream and stores them in the string str. The fgets()
terminates as soon as it encounters either a newline character or end-of-file or any other error.
However, if a newline character is encountered it is retained. When all the characters are read
without any error, a '\0' character is appended to end the string.
● FILE *fp;
● char str[80];
fp = fopen("Student.DAT", "r");
● if(fp==NULL)
● {
● printf("\n The file could not be opened");
● exit(1);
● }
● while (fgets(str, 80, fp) != NULL)
● printf("\n %s", str);
● printf("\n\n File Read. Now closing the file");
● fclose(fp);