Вы находитесь на странице: 1из 15

Unix, C & C++ UNIT III

Snapshot
Introduction to Structure Declaration of Structure Array of Structure Pointers & Structure Unions Introduction to Disk I/O Text mode unformatted I/O functions Line Input and Output Text mode formatted I/O functions Binary mode I/O functions

3.0

Introduction

This chapter is concerned with the use of structures within a C program. How structures are defined, and how their individual members are accessed and processed within a program. The relationship s between structures and pointers, arrays and functions will also be examined. Closely associated with the structure us the union, which also contains multiple members. Unlike a structure, however, the members of a union share the same storage area, even though the individual members may differ in type. In addition, this chapter is concerned with only with stream oriented data files.

3.1

Objective

The objective of this chapter makes the learner aware of the fundamentals structures and Disk I/O functions. The fundamental concepts include structure, array of structure, nested structure, pointers and structure and unions. Towards end of this chapter the student can get the basic knowledge about structures and Disk I/O functions.

3.2
3.2.1

Content

Structure The main use of structure is to lump together collections of disparate variable types, so that they can conveniently be treated as a unit. For example, while writing a compiler or assembler, one might need for each identifier information like its name (a character array), its source line number (an integer), some type information (a character, perhaps) and probably a usage count (another integer). char id[10]; int line; char type; int usage;

Page 36

Unix, C & C++


In this case, the structure is first defined, that is, what kinds of things it contains; after that one can actually reserve storage for it, either in the same statement or separately. The simplest thing is to define it and allocate storage all at once. struct { char id[10]; int line; char type; int usage; } sym; This defines sym to be a structure with the specified shape; id, line, type and usage are the members of the structure. 3.2.1.1 Declaration of Structure

Before a structure is used, it has to be declared. The syntax for structure is as follows: struct <structure name>{ Data_type Data_type Data_type . . Data_type }; Once, the new structure data type has been defined one or more variable can be declared of that structure type. Consider a structure declared as follows: struct student { char name[10]; int rollno; char sex; /* m or f */ int age; }; This defines a new data type called student to be a structure with the specified shape; name, rollno, sex and age. A variable of type struct student can be declared as follows : struct student collegestu, schoolstu; This statement allocates space in memory and makes available space to hold structure elements. A structure can be declared in any of the format given below. structure_element 1; structure_element 2; structure _element 3; structure_element n;

Page 37

Unix, C & C++

Format one: struct student { char name[10]; int rollno; char sex; int age; }; struct student collegestu,schoolstu; Format two: struct { char name[10]; int rollno; char sex; /* m or f */ int age; } collegestu, schoolstu; 3.2.1.2 Accessing and Initialization of Structure

Structure variable uses dot (.) operator to access structure element. Syntax to access the structure elements is structure_name . structure_element_name for example, To set the value to the structure element collegestu.rollno = 1125; collegestu.age = 21; for example, To take the value from the structure element int rnumber = colledestu.rollno; int stuage = collegestu.age; The following program illustrates how structure members can be accessed. #include<stdio.h> struct stud { int rno; char name[20]; }; main() {

Page 38

Unix, C & C++


struct stud s; printf(Enter the students name:); scanf(%s,s.name); printf(Enter the students roll number:); scanf(%d,&s.rno); printf(The students details are:\n); printf(Name : %s\n,s.name); printf(Roll No. : %d\n,s.rno); } Output: Enter the student's name:Adithya Enter the student's roll number:100 The student's details are: Name : Adithya Roll No. : 100 The above program accesses the members of the structure by declaring a structure variable and accessing each member using a dot operator. In the above program, the structure members name and rno are accessed using the structure variable s and dot operator. 3.2.1.3 Array of Structure

Just like an array of variable, an array of structure can also be declared. Suppose a symbol table for 100 identifiers has to be made. The definitions can be extended like char id[100][10]; int line[100]; char type[100]; int usage[100]; but a structure lets rearranging this spread-out information so that all the data identifier is collected into one lump: struct { char id[10]; int line; char type; int usage; } sym[100]; This makes sym an array of structures; each array element has the specified shape. Now, members can be referred to as sym[i].usage++; /* increment usage of i-th identifier */

Page 39

Unix, C & C++


for( j=0; sym[i].id[j++] != '\0'; ) ... etc. Thus, to print a list of all identifiers that have not been used, together with their line number, for( i=0; i<nsym; i++ ) if( sym[i].usage == 0 ) printf("%d\t%s\n", sym[i].line, sym[i].id); 3.2.1.4 Nested Structure

It is possible to declare a structure inside another structure. This means a structure can be made a member of another structure. The following program uses a structure called date as a member of another structure. #include<stdio.h> #include<conio.h> struct date { int dd; int mm; int yy; }; struct stud { char name[20]; struct date d; int m1,m2,m3; float per; }; main() { struct stud s; printf("Enter the Details of student\n"); printf("\nName:"); scanf("%s",s.name); printf("\nDate of Birth(dd mm yy):"); scanf("%d%d%d",&s.d.dd,&s.d.mm,&s.d.yy); printf("\nMarks in 3 Subject:"); scanf("%d%d%d",&s.m1,&s.m2,&s.m3); s.per=(s.m1+s.m2+s.m3)/3; printf("\nStudent Result"); printf("\n%s has secured %f%%",s.name,s.per); getch(); Page 40

Unix, C & C++


} Output: Enter the Details of student Name:Ashwin Date of Birth(dd mm yy):12 12 1980 Marks in 3 Subject:98 97 95 Student Result Ashwin has secured 96.000000% 3.2.1.5 Pointers and structure

Consider a block of data containing different data types defined by means of a structure. For example, a personal file might contain structures, which look something like: struct tag { char lname[20]; /* last name */ char fname[20]; /* first name */ int age; /* age */ }; Just like a variable of type structure, a pointer variable of type structure can also be declared. The following program declares a pointer variable of type struct tag and uses this pointer variable to access every member of the structure. #include<stdio.h> struct tag { char lname[20]; char fname[20]; int age; }s; main() { struct tag *t; t=&s; printf(\nEnter the first name:); scanf(%s,t-> fname); printf(\nEnter the last name:); scanf(%s,t-> lname);

Page 41

Unix, C & C++


printf(\nAge:); scanf(%d,&t->age); printf(\nThe details are:); printf(Name:%s %s\nAge:%d, t-> fname, t-> lname,t->age); } Output: Enter the first name:Mahatma Enter the last name:Gandhi Age:60 The details are:Name:Mahatma Gandhi Age:60 3.2.2 Unions

A union is similar to a structure, except that it shares storage space between different members. union union_name { type variable-names ; ... }union_variables ; Example union int_or_long { int i; long l; } a_number; Unlike a struct, the variables a_number.i and a_number.l occupy the same location in memory. Thus, writing into one will overwrite the other. Elements of a union are accessed in the same manner as a struct. 3.2.3 File Handling

Files are very useful in storing information for future analysis and retrieval. C language defines a number of functions for handling files. Basic file handling Program When a file has to be used either for writing to it or for reading from it, it has to be opened in corresponding mode. The function fopen()is used for opening a file; certain

Page 42

Unix, C & C++


systems may also provide specialized ways of opening streams connected to I/O devices in a more exotic ways. a. fopen() A successful call to fopen returns a pointer of type FILE *, that is, pointer to FILE, where FILE is a special type defined by <stdio.h>. A FILE * (also called file pointer) is handled by which an I/O stream in C is referred. I/O functions which do not assume standard input or standard output accept a FILE * argument telling them which stream to read from or write to. The prototype of fopen is as follows: FILE * fopen(char *filename, char *mode) Here, The first string is the file name, which can be any string (simple filename or complicated pathname) which is acceptable to the underlying operating system. The second string is the mode in which the file should be opened. The simple mode arguments are 1. r - open for reading 2. w - open for writing (truncate file before writing, if it exists already) 3. a - open for writing, appending to file if it exists already When a file has to be used for both reading and writing, the operator + can be used. Thus modes r+ and w+ lets reading and writing to the file. However, both cannot be done at the same time; To read or write the read/write indicator must be explicitly repositioned. A normal program in C using files often uses most of the statements used in the sample program given below : #include <stdio.h> main() { FILE *fptr; fptr = fopen(sample.dat,r+); if (fptr == NULL) printf(Cannot open the file); else printf(File opened successfully); fclose(fptr); } Output: (Assuming the file sample.dat exists) File opened successfully Page 43

Unix, C & C++

3.2.3.1

Text mode Unformatted I/O functions

It is simple to input or output a single character at a time and C has certain functions which accept or prints a single character at a time. The getchar() function reads the next character from the standard input; getc(fp) reads the next character from the stream fp. Both return the next character and if the next character cannot be read, the noncharacter constant EOF is returned. Similarly, the function putchar(c) writes the character c to standard output; putc(c, fp) writes the character c to the stream fp. The following program, illustrates how the functions getchar() and putc() can be used to accept the character from the user and copy those contents into a file respectively. #include<stdio.h> main() { char c; int i; FILE *fp; fp = fopen(dat.txt,w+); printf(Enter the characters); while ((c= (char)getchar( ) )!= 0) putc( c,fp ); } Input: Enter the characters God helps those who help themselves 0 The following program illustrates how the functions getc() and putchar() can be used to read information from a file and display it on the screen : #include<stdio.h> main() { int c; FILE *fp; fp= fopen(dat.txt,r+); while((c=getc(fp))!=EOF) putchar( c ); } Output: God helps those who help themselves The above program would continue to read characters from the file and prints them on the screen till the EOF (End of File) is reached.

Page 44

Unix, C & C++

3.2.3.2

Line Input and Output (fgets, fputs, etc.)

The function gets() and puts() offer a simple alternative to the use of scanf() and printf() for reading and displaying strings. In the case of gets(), the string will be entered from the keyboard and will terminate with a newline character. char* gets(char *line) reads the next line of text from the standard input and places the characters in the character array pointed to by line. It returns a pointer to the line, unless it reaches end-offile, in which case it returns a null pointer. The function int puts(char *line) writes the string pointed to by line to the standard output and writes a \n to terminate it. It returns a nonnegative value unless there is some kind of a write error, in which case it returns EOF. The following example illustrates the use of gets and puts. #include<stdio.h> main() { char line[80]; gets(line); puts(line); } Output: How are you? How are you? The function int fputs(char *line, FILE *fp) writes the string pointed to by line to the stream fp. Like puts, fputs returns a nonnegative value or EOF on error. Unlike puts, fputs does not automatically append a \n. Here is a program which demonstrates the use of fputs(). #include<stdio.h> #include<conio.h> Page 45

Unix, C & C++


main() { FILE *a; char b[21]="This is a test"; a=fopen("t.t","w+"); fputs(b,a); getch(); } Output: The program has no output. It writes the text to the file The function char *fgets(char *line, int max, FILE *fp) reads the next line of input from the stream fp and places the characters, including the \n, in the character array pointed to by line. The second argument, max, gives the maximum number of characters to be written to the array and is usually the size of the array. Like gets, fgets returns a pointer to the line it reads or a null pointer if it reaches end-of-file. Unlike gets, fgets does include the \n in the string and it copies to the array. Therefore, the number of characters in the line, plus the \n, plus the \0, will always be less than or equal to max. In the following program, the file t.t contains 17 characters. The function fgets accepts a number which is 1 more than the number of characters to be read.That is why it accepts18 since it has to be more. #include<stdio.h> #include<conio.h> main() { FILE *a; char c[21]; a=fopen("t.t","r+"); fgets(c,18,a); printf("The text from file is :\n %s",c); } Output: The text from file is: This is a test

Page 46

Unix, C & C++


3.2.3.3 Text mode Formatted I/O functions

Similar to the functions printf() and scanf(), there are equivalent function which read or write data to files. These are called fprintf and fscanf and take the file pointer as an additional first argument. Consider the following example, #include<stdio.h> FILE *fptr; void main() { fptr = fopen(temp.txt, w+); fprintf(fptr,Hello world\n); fprintf(fptr,This line contains numbers : %d\n,20); fprintf(fptr,%d,30); } Executing the above program result in a file called temp.txt containing the following text Hello world This line contains numbers: 20 30 The following program illustrates reading from a file using fscanf ( ) #include<stdio.h> FILE *fptr; void main() { int x; char ch[80]; fptr = fopen(temp.txt, r); fscanf(fptr,%s,ch); printf(%s, ch); fscanf(fptr,%s,ch); printf(%s, ch); } Output: Helloworld When the above program is executed, it reads the data from the file called temp.txt and displays the content of the file. 3.2.3.4 Binary mode I/O Functions

Page 47

Unix, C & C++


Binary or b mode means that no translations are done by the stdio library when reading or writing the file. Normally, the newline character \n is translated to and from some operating system dependent end-of-line representation (LF on Unix, CR on the Macintosh, CRLF on MS-DOS, or an end-of-record mark on record-oriented operating systems). On MS-DOS systems, without binary mode, a control-Z character in a file is treated as an end-of-file indication; neither the control-Z nor any characters following it will be seen by a program reading the file. In binary mode, on the other hand, characters are read and written verbatim; new line characters (In MS-DOS, control-Z characters) are not treated specially. Binary files are mainly used in image handling programs. For general purposes, it is strongly recommended to use text files/text mode I/O operations.

3.3

Revision Points

Structure A structure is a collection of variables under a single name. These variables can be of different types, and each has a name which is used to select it from the structure. A structure is a convenient way of grouping several pieces of related information together. Union A union is a memory location that is shared by two or more different types of variables. A union provides a way of interpreting the same bit pattern in two or more different ways. Declaring the union is similar to declaring the structure. File Pointer A file pointer is pointer to a structure of type FILE. It points to information that defines various things about the file, including its name, status, and the current position of the file.

3.4

Intext Questions
1. What is a structure? How does a structure differ from an array? 2. What is structure member? What is the relationship between a structure member and a structure? 3. How is an array if structures initialized? 4. What is a union? How does a union differ from a structure? 5. What is the primary advantage to using a data file?

3.5

Summary
A pointer in C refers to a variable that holds the address of another variable.

Page 48

Unix, C & C++

The main use of structure is to lump together collections of disparate variable types, so that they can conveniently be treated as a unit. A union is similar to a structure, except that it shares storage space between different members. Files are very useful in storing information for future analysis and retrieval. C language defines a number of functions for handling files.

3.6

Terminal Exercises
1. How can structure variables be declared? How do structure variable declarations differ from structure type declarations? 2. How is a structure member accessed? How can a structure member be processed? 3. What happens when a pointer to a structure is incremented? 4. Summarizes the different types of files that can be specified by the fopen function. 5. For what kinds of applications are unformatted data files well suited?

3.7

Supplementary Materials
1. Schildt, C++: The Complete Reference, Third Edition, TMH, 2000. 2. Byron Gottfried, Programming with C, Second Edition, TMH, 1998.

3.8

Assignments
1. Summarizes the rules that apply to processing unions. Compare with the rules apply to processing structures. 2. Describe two different approaches to updating a data file. Which approach is better, and why?

3.9

Suggested Reading/Reference Books/Set Books


1. Venugopal and Prasad, Programming with C, TMH, 2001. 2. Balagurusamy, Programming in ANSI C, TMH, 1992.

Page 49

Unix, C & C++

3.10 Learning Activities


1. Collect information on Structures and union (not covered in this chapter) from the internet. 2. Collect information on Disk I/O functions.

3.11 Keywords
Structure Union fclose fgets fscanf Struct fopen fputs fprintf MS-DOS

Page 50

Вам также может понравиться