Академический Документы
Профессиональный Документы
Культура Документы
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
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
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
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
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
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
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
3.2.3.1
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
3.2.3.2
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
Page 46
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
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
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
Page 49
3.11 Keywords
Structure Union fclose fgets fscanf Struct fopen fputs fprintf MS-DOS
Page 50