Module 5

You might also like

Download as pdf
Download as pdf
You are on page 1of 23
oP 13) 0 MODULE 5 Structure and Fil 5.1 Introduction to Structure: Structure is basically a user defined data type th: (even of different data types) together. A structure is same as that of records. It stores related information about an entity. The major difference between a structure and an array is that an array contains related information of the same data type can store related information 4 Siructure is, therefore, a collection of variabies under a within a structure are 6f different data types and each has select it from the structure. The variabl na name that is used to 5.1.1 Structure Declaration ¢ is declared usi keyword struct followed by 2 the ‘variables of the structures are declared within the structure. A structure type is defined by using the given syntax «struct struct-name | data_type var-name; data_type var-name: For example, if we have to define a structure for a student, then the related information probably would be: roll_number, name, course, and fees. This structure can be declared as: struct student int no; char name(20}; char course[20]; float fees; able name declared within a structure is called a member of the structure. The structure definition does not allocates any memory. It just gives a template that conveys to the C compiler how the structure is laid out in memory and gives details of the member names. Memory is allocated for the structure when we Geclare a variable of the structure. For ex, we can define a variable of student by writing struct student stud]; Here, struct student is a data type and stud] is a variable. Look at another way of declaring variables. In the following syntax, the variable is declared:at the time of structure declaration. struct student (int rno; char name[20}; char course(20] float fees; Jstud1, stud2; In this declaration we declare two variables stud and stud2 of the type student. So, if you want to declare more than one variable of the structure, then separate the Maharaja Institut of Technology Mysore. Dept. of Computer Seienc variables using a com nd Ene. | © scanned with OKEN Scanner Principles af P r rograminy na C (22POP 13) 5.1.2 typedef Declarations he tpedef fderived fom type definati t : eee ' lion) keyword enables the programmer to create a By using typedef, no new da data type. Vis created, rather an alternate name 1s given to known The neral svntax of using the typedef keyword is given as typedef existing data type new data type. Notes that types typedef stater new type. For example, if we write typedef int INTEGER ‘ name of data type int. To declare variables using the new precede the variable name with the dat t does not occupy any memory, it simply defines a then INTEGER data wp! e net name ‘a type name. When we pre sith twpedet keys hen we precede a struct name with typedei keyword, then the struct becomes a new wpe. It is used to make the construct shorter with more meaningful names for types already defined by C or for types that you have declared. With a typedef declaration, becomes a synonym for t : For example, writing typedef struct student ‘ int r_no; char name(20}; char course[20}; float fees; Now that you have preceded the structure's name with the keyword typedef, the student becomes a new data type. Therefore, now you can straight away declare variables of this new data type as you declare variables of type int, float, char, double. etc. to declare a variable of structure student you will just write, student stud1; 5.1.3 Initialization of Structures A structure can be initialized in the same w Initializing a structure means as: structure. When the user docs not explicitly initializes the structure then C auton that. For int and float members, the values are initialized to z members are initialized to the ‘\0" by default. s other data types are initialized. igning some constants to the members of the tically does and char and string, The initializers are enclosed in braces and are separated by commas. Note that initializers match their corresponding types in the structure definition. ‘The general syntax to initialize a structure variable is given as follows, struct struct_name | data_type member namel; data_type member name2; data type member_name3; jstruct_var {constantl, constant2, constant 3, OR 1 Es) © scanned with OKEN Scanner Dept. of Computer Science and Engs. Teouneia tmerinne of Technology Mysore. Principle of Programming Using C (22POP13) 0 struct struct_name | data type member namel; data type me 2; data_type member_name3; struct struct_name struct_var = {constant1, constant2, struct student stud = {01, “Rahul”, “BCA”, 45000}; 3.1.4 Accessing the Members of a Structure Each member of a structure can be used just like 2 normal variable, but its na will be a bit longer. A structure member variable is generally accessed using a’ (dot operator}. The syntax of accessing a structure a member of a structure is: struct_var.member_name For ex, to assign value to the individual data members of the structure variable Rahui. we may write, stud 1.r_no = 0) strepy(stud name, “Rahul’); stud L.course = “BCA’ stud] fees = 45000; To input values for data members of the structure variable stud1, we may write scanf(“%d", &stud1.r_no); scan{(‘%s", stud ].name); Similarly, to print the values of s print{("%s”, stud cour: printf(%f", stud l fees); ructure variable stud1, we may write, d only when we declare variables of the structure. Memory is allocé 5.1.5 Copying and Comparing Structures We can assign a structure to another structure of the same type. For ex, if we have two structure variables stul and stud2 of type struct student given as struct student stud] = (01, “Rahul, "BCA", 45000} struct student stud2, ‘Then to assign one structure variable to another we will write, stud2 = stud]; C does not permit comparison of one structure variable with another, However individual members of one structure can be compared with individual members of another structure. For example to compare the fees of two students, we will write If(stud 1 fees > stud2.fees) 5.1.6 Finding the Size of a structure There are three different ways, through which we can find the structure will occupy in the memory. 1. Simple Addition: In this technique, we will make a list of all data type: the memory required by each. For example: struct student t number of bytes a nd add ‘ence and Boas. | | (& scanned with OKEN Scanner Maharaja Institute of Technology Mysore. Dept. of Computer A A Principles of ogramming Using C (aOR 13} int r_no; char name[20}; char course[20}; float fees; 2 ze of r_no ze of name = 20 x Size of Character Size of course = 20 x Size of Character Size of fees = ‘Therefore, Size 2+20+20+4 = 46 Bytes 2. Using sizeof Operator sizeo? operator is used Now, the size of r_no + size of the name * size of the Cours to calculate the size of a 2022 data wpes, vari expression. To use this operator simply write sizeof(structure name); For example: #include struct student int r_no; char name(20}; char course[20]; float fees; iy void main() t struct student std; printf{‘Size of Student is d\n" sizeof(std)); } 3. Subtracting the Addresses In this technique, we use an array of structure ariables. Then we subtract the address of the first element of next consecutive variable from the address of the first element of preceding structure variable. Write a program using structures to read and display the information about a student #include int main() {struct student { int roll_no; char name(80}; float fees; char DOB[80); b struct student stud]; prinu(*\n Enter the roll number scanf{("%d”, &stud 1 .roll_no); print{(*\n Enter the name scan{("%s", stud1.name}; print{(*\n Enter the fees : scanf(“%f", &stud fees); Maharaja Institute of Technology Mysore. Dept. of Computer Science and Enge. | BL (& scanned with OKEN Scanner ples of Program printi’\n Enter the DOB : *) seanf{’’ss”, stud 1. DOB), ef printif’\n ROLL N printf{*\n ROLL No. 5.2 Nested Structure structure can be placed within another structure. That is nother structure as its member. Such a structure that contains member is called a nested structure typedef struct char first_name[20]; char mid_name|20}; char last_name[20]; Al typedef struct int dd; int mm; int ys \DATE; struct student stud]; studl.name.first_name = “Janak”; studl.name.mid_name studl.name.last_name studl.course = “BCA”; stud1.DOB.dd = 1 stud1.DOB.mm = 09; stud1.DOB.yy = 1990; studl.fees = 45000; “Raj”; Write a program to read and displa within a structure #include void main() struct DOB int day; int month; int year; struct student int roll_no; char name|100); ty STUDENT'S DS PAILS print{(*\n ROLL No, = %d”, stud 1 roll_no} 1 NAME, = %s", stud 1 name} oF, stud 1 fe ", stud |. DOB); “Thareja” information of a a structure may contain nother structure as student using structure Mahoraia Instivute of Technology Mysore. jence and Ene ‘EO ; (& scanned with OKEN Scanner Hoat fees: sirnet DOR date: struct student stud]; prinu("\n Enter the rol! number : “}: ) scanf(-%d”, &studlroll_no} printi(*\n Enter the name : *) scanf{'%s", stud name} printfl*\n Enter the fe scanf{'%t", Sstud l fees printf(*\n Enter the DOB : *); scani{‘%d %d %d”, &stud 1 date.day. &stud | date.month, &stud 1 date.vear) prinu{‘\n *******STUDENT'S DETAILS "7"""*"): printf(*\n ROLL No. = %d", stud .roll_no): printi[’\n NAME. = Ss". studi .nam print{("\n FEES. = %", stud] fees); printf{‘\n DOB = %d - %d - %d", studl.dateday, stud!.date.month, stud] .date.year); 5.3 Arrays of Structure In a class, we do not have just one student. But there may be at least 30 students. So the same definition of the structure can be used for all the 30 students, This would be possible when we create an array of structure, ‘The general syntax for declaring an array of structure can be given as, struct struct_name { datatype member_namel; data_type member_name2; data type member_name3; struct struct_name struct.var[indes}; Consider the given structure definition: struct student. int r_no; char name[20j; 70 char course[20}; 20 float fees; 4 i 4b ‘A student array can be declared simply by writing ‘struct student stud|30);, Now, to assign values to the i student of the class, we will write +) stud{ij.r_no = 09; ‘stud|i].name = “RASHT’, stud[i].course = *MCA"; studfij.fees = 60000; oe Deni. of Computer Science and Eng. | Ws © scanned with OKEN Scanner Principies of Progra ing Using © (22POPIS) Write a program to read and display information of all the students in the class. dincludeestdio. b> void main() struct student int rall_no; char name|80|; float fees; char DOB|SO|: struct student stud[50} int n, is printi("\n Enter the number of students : 5 seanf(t%d". fn): O:i typedef struct int x; int y; \POINT; void display(int, int); void main(} POINT pl = {2, 3 display(p 1.x, p1.y); return 0; 1 void display( int a, int b) t printf("%d %d", a, b); 1 5.4.2 Passing Individual Member 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 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 ven below passes a structure to-the function using call-by-value method. #include typedef struct t int x5 int y; }POINT; void display(POINT); void main() { POINT pl = (2, 3}; display(p 1); return 0; } void display( POINT p) { } printf("%d %d", p.x, p.y}; Science and Enee. | NESE! (& scanned with OKEN Scanner Maharaia Inctinite nf Technalowy Musnre Dent, of Comput Principles of ! 5.4.2 Passing Structure Through Pointers, C allows to cr ea pointer to a structure Like in other cases, a pointer to a structure estrcture, but merely @ variable that holde the address of a structure The syntax to declare a pointer to a structure can be struct struct_name data type member_name1; data type member_name2; ptr OR struct struct_name *ptr; For our student structure we can declare a pointer variable by writing struct student *ptr_stud, stud; The next step is to assign the address of stud to the pointer using the address operator (8). So to assign the address, we will write ptr_stud = &stud; o access the members of the structure, one way is to write /* get the structure, then select a member */ (*ptr_stud).roll_no; ‘An alternative to the above statement can be used by using ‘pointing-to’ operator (->) as shown below /* the roll_no in the structure ptr_stud points to */ ptr_stud->roll_no = 01; Write a program using pointer to structure to initialize the members _in the structure. #include struct student char name(20]; char course[20}; float fees; void main() {struct student stud], *ptrstud]; ptr_studl = &stud]; ptr_studl->r_no = 01; strepy(ptr_stud 1->name, “Rahul") strepy(ptr_stud 1->course, BCA"); ptr_studl-rfees = 45000; print{(’\n DETAILS OF STUDENT"); print{("\n - aaeee'hy printi(\n ROLL NUMBER = %d", ptr_stud1-2r_no); prin(\n NAME. =", puts(ptr_stud L->name print((\n COURSE =", puts(ptr_stud 1 ->cour print{(\\n FEES = %f", ptr_stud 1 ->fe Maharaja Institute of Technology Mysore. Dept. of Computer § nce and Engst. | [BS (& scanned with OKEN Scanner so ports) crvoanan NS ere panaiptes oF | peference data contains a For example to data of it a pointer 1 8 i Squall’. self-referential structure : ‘a types. 36 Ori ojjection of variables of different data © Similar to structures, 4 union is & collection 0 as ae gnions ea cae The only difference between & structure and a union js that in C# only store information 1 ‘one field at any One Time of memory shat is weed © To better understand union, think of it as a chu! oe fendi ie veting store variables of different types. When a new value sig) is ct vi e new data. , F hat data is replaced with the new ¢ oh yeas plications tha ions ney are useful for AP! ‘Thus unions are used to save memory. “y fal for ape cat involve multiple members, Ginere values niced not Be assign one time a structure. The only 6.1 Declaring a Union : : i ame as that of declaring ould be Fae syntax for declaring @ Unio® is si u “Miference is that instead of using the keyword struct, the keyword union used. The syntax for union de ‘union union-name claration can be given 85 data_type var-nam data type var-name; i Again, the typedef keyword can Pe used to simplify the declaration of union variables. about a union is that the size of an union ‘The most important thing to remember e Muincient number of bytes must be the size of its largest field. ‘This is, becaus ine arved to store the largest sized field 5.6.2 Accessing a Member of a Union Soe ber 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 mame aetewed by the dot operator followed by the member name. 5.6.3 Initializing Unions wieisan corto one lize any other union member except the first member . ‘ Saat ieee between a structure and a union is that in case of a union, the fe fa share the same memory ‘space, so fresh data replaces any existing a. Lo @ code given below and observe the di etween a - Look at th s difference between 4 structure and union when: their fields are to be initialized. : “ ns denge | BRL] Deot. of Computer Science (& scanned with OKEN Scanner Principles of Ir ng Using © (22POP LY #includesstdio. wpedef struct POINT! int x, 3 typedef union POINT? im x: main() POINT! P Mlegeal with union prinu{("\n The co-ordinates of P! are od and 96d! printif’\n The co-ordinates of P2 are %d and %d", P2. return 0: OUTPUT ‘The co-ordinates of Pl are 2 and 3 ‘The co-ordinates of P2 are 5 and 5 5.7 Arrays of Union Variables Like structures we can also have array of union variables. However, because of the oblem of new data overwriting existing data in the other fields, the program may not display the accurate results. #include union POINT int x, Yi void main() 1 POINT points[3}; ts [0]. points[O].y = points[2] " ordinates of Points|%dJ are %d and %d", i, points[i).x, points|il-y): print("\n C ourpuT Co-ordinates of Points[0] are 3 and 3 Co-ordinates of Points[1] are 5 and S Co-ordinates of Points[2] are 7 and 7 5.8 Unions inside Structures Union can be very useful when declared inside @ structure, Cov which you want a field of a structure to contain @ string or an integer, depending on what the user specifi uch a scenario. - struct student ler an example in rer ute of Technolopy Mysore © scanned with OKEN Scanner (eevor sy Pnnerples ol Progt ig Using ¢ har name| 20) nt roll_no, rks nar nainti struct student stud shar choice srint{(\n You can enter the name or roll number of the inti’ \n Do you want io enter the name? (Yes or No) : gets(choice): fichoice==y | | choice==Y) rinti\n i geis(stud.name): print{("\n Enter the roll number : °) scanf("%d", & oll prin(’\n Enter the marks : scanf("%d", &stud.mark if(choice=='y' || choic printi(’\n Name : %s°, stud.name); else printi(’\n Roll Number : %d ", stud.roll_no}; printf(’\n Marks : Yd", stud.marks}; 5.9 Structures inside U: C also allows users to have a stiucture within a union. typedef struct a int marks; char name|20]; typedef struct b int marks; int roll_no; typedef union Student struct a A; struct b B; h Similarities between Structure and Union. student} c 1, Both are user-defined data types used to store data of different types or arrays. A member can also consist of a bit field. nstinite of Trehnelaoy Musore, Deot. of Compute can be objects of any type, including other structures and unions nce and Ene. | © scanned with OKEN Scanner Principles of Programming Using C (221 Differences between Structure shown below as 5.9 Enumerated Data Types OPIS) Both structures and unions support only as two structures or tinions in the assignment must have the ment — and sizeof opera ‘ame members and member types. A structure or a union can be passed by value to Lunetions and returned by value by functions. The argument must have the same type as the function parameter. structure or union is passed by value just like a scalar variable as a corresponding arameter +." operator or selection operator, which has one of the highe: Used for accessing member variables inside both the user-defined dat and Union are as shown below in tabular ences, i types. follows: Keywors 1 | | | gene So sceefenen |_Srerettememt | Grargestmems= J Memory | Eacnmembenwisinastocu Teor anos ‘atv | Afenngineyatueotamemberwieta “aerngievaueetanyet ne mere | | Ateting_| emeerernesucze anerervaies | \ t | [Aecessita |" asacualmerewcanteacenssedatatne | oniyene membercanteaccesseaat atime | L : 1 a of a structure caninitialize atonce just member of aunion can be init © The enumerated data type is a user defined type based on the standard intege type. © An enumeration consists of a’ set of named integer constants. That is, in ai enumerated type, each integer value is assigned an identifier. This identifier (also known as an enumeration constant) can be used as symbolic names to make the program more readable * To define enumerated data types, cnum keyword is used. + Entimerations create new data types to contain values that are not limited to the values fundamental data types may take. The syntax of creating an enumerated data type can be given as below. enum enumeration_name { identifier1, identifier2, identifiern }; « Consider the example given below which creates a new type of variable calle, COLORS to store colors constants. ‘ enum COLORS {RED, BLUE, BLACK, GREEN, YELLOW, PURPLE, WHITE}; In case you do not assign any value to a constant, the default valte for the first one in the list - RED {in our case), has the value of 0. The rest of the undefined constants have a value | more than its previous one. So in our example, * RED = 0, BLUE = 1, BLACK = 2, GREEN = 3, YELLOW = 4, PURPLE WHITE =6 «Ifyou want to explicitly assign values to these integer constants then you s| specifically mention those values as shown below. * enum COLORS {RED = 2, BLUE, BLACK = 5, GREEN = 7, YELLOW, PURPLE , WHITE = 15}; ‘ \e e © Asa result of the above statement, now $ ould TTanaraja instar oF Peony Mysore: Dip of Computer Sconce and Ene 1 EN © scanned with OKEN Scanner Principles of Programming sing 2 (22POP 13) RED = 2, BLUE = 3, BLACK = 5, GREEN = 7, YELLOW = WHITE = 15 5.10.1 enum variables The syntax for declaring a variable of an enumerated data Soto quumeration name variable_name: So to create a v; ’ ‘ariable of COLORS, we may write enum COLORS bg color; - Another way to declare a variable can be enum COLORS {RED, BI ype can be given as, as illustrated in the statement below. LUE, BLACK, GREEN, YELLOw, PURPLE, WHITE}bg color, fore color; : a 5.10.2 Using the Typeder Keyword C permits 1 ‘0 use wpedef keyword for e: typedef enum COLORS color; Then, we can straight-away declar variables by writing color forecolor = RED; numera ied data wpes. For ex, if we write 5.10.3 Assigning Values To Enum. Once the enumerated variable has beer ie jared, values can be stored in it. However, desttmerated variable can hold only declared values for the type. For example, to assign the color black to the back ground color, we wit write, bg_color = BLACK; Once an enumerated v; another variable ‘erated Variables auasoelhas/beentassignedta Value, we carl store: its value in of the same type as shown below. enum COLORS bg color, bg_color = BLACK; border color = bg color; border _color; 5.10.4 Enumeration Type Conversion Enumerated types can be: implicitly or explicitly cast implicitly cast an enumerated type to However, when we implicitly either generate an error or wai For : an integer when required. cast an integer to an enumerated type, the compiler will ming message. the compiler can 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, ¢ is an enumerate data type variable. If we write, ¢ = BLACK + WH logically, it should be 2 + 6 = 8; which is basically a value of type int. How: hand side of the assignment operator is of the would complain an error. » then ever, the left type cnum COLORS. SO the statement To remove the error, you can do cither of two things. First, declare c to be an int. Second, cast the right hand side in the following manner. : © = enum COLORS(BLACK + WHITE}; ‘ing Enumerated Types ieee areas go-egemnbonen ——LDLrt~— type. Look at the following statements which illustrate this concept. bg_color = (enum COLORS)6; if{bg_color == WHITE) Zomputer Science and Ei Maharaia Institute of Technology Mysore. Dept. of Comput ni es | EES) (& scanned with OKEN Scanner +o Principles of Programming Using C 22POP13) 202 fore color = BLUE; fore_color = BLUE; if{bg_ color == fore color} printf("\n NOT VISIBLE"); Since enumerated types are derived from integer type. they can be used in a switch- case statement, enum {RED, BLUE, BLACK, GREEN, YELLOW, PURPLE, WHITE}bg_color; switch(bg color) case RED: case BLUE: case GREEN: printf{’\n It is a primary color"); case defaw printf{"\n It is not a primary color"); break; o 0.6 Input/Output Operations On Enumerated Types” ‘Singe enumerated types are derived types, they cannot be read or written using formatted 1/0 functions available in C. When we read or write an enumerated type, We read/write it as an integer. The compiler would implicitly do the type conversion as discussed earlier. scum COLORS|RED, BLUE, BLACK, GREEN, YELLOW, PURPLE, WHITE); enum COLORS ¢; scanf{"%d", &c}; printf{"\n Colo! Veh FILES 5.11 Introduction to Files ® file is a collection of data stored on a secondary storage device like hard disk. A file is. aie ails used because real life applications involve large amounts of data and in such situations the console oriented 1/O operations pose two major problems Waist, it becomes cumbersome-and time consuming to handle huge amount of data through terminals. «Second, when doing 1/0 using terminal, the entire data is lost when either the program is terminated or computer is turned off. Therefore, t becomes necessary PO store data on a permanent storage (the disks) and read when without destroying the data 5.11.1 Streams in C In C, the standard streams are termed as pre-conn between a text terminal and the program (when it be is.a logical interface to the devices that are connected to the computer: ‘stream is widely used asa logical interface to a file where a file can refer to a disk fle, the computer screen, keyboard, ctc. 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). Maharaja Institute of Technology Mysore. Dept of Computer Science and En (& scanned with OKEN Scanner y2VOV13) — programming Using © (2: Principles of P KEYBOARD i ‘PROGRAM SCREEN \ § the stream from which the program fer of data using the read unless redirected, © Standard input (stdin); Standard input t: receives its data. The program requests (rans operation. However, not all programs require input Generally input for a program is expected from the keyboard + Standard output (stdout): Standard output is writes its output data. The program requesis data operation. However, not all programs generate output. «Standard error (stderr): Standard error is basically an output stream used by programs to report error messages or diagnostics. It is a stream independent of eeehinrd output and can be redirected separately. No doubt, the standard ouput 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 rogram he stream where @ sfer using the write 5.11.2 Buffer Associated with File Streams When a stream linked to a disk file is created, a buffer is automatically created and Associated with the stream. A buffer is nothing but a block of memory that is used for temporary storage of data that has to be read from or written to a file. Buffers are needed because disk drives are block oriented devices as they can operate efficiently when data has to be read/ written in blocks of certain size. The size of ideal buffer size is hardware dependent. ‘the buffer acts as an interface between the stream (which is character-oriented) and the disk hardware (which is block oriented). When the program has to write data to the Stream, it is saved in the buffer till itis full. Then the entire contents of the buffer arc written to the disk as a block. Data from the Prograin writes buffer is written to tata baller the disk fle Ro | ae a Similarly, when reading data from a disk file, the data is read as a block from the file dad 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. 5.11.3 Types of Files « Inc, the types of files used can be broadly classified into two categories- text files and binary files. 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. (& scanned with OKEN Scanner SE TnITeTTETTRTET TETTTTTTTTETTETIETTIT ITE TTT TTT [incites of Programunng Using C (22POP 13) «Because text files only process: characters, they can only read or write data onc character at a time = Inatest file, ca camtains gero 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 o! 235 characters. « Aline in a text file is not ac string, so it is not terminated by a null charact When data is written to a text file, each newline character is converted to a carriage felurn/line feed character. Similarly, when data is read from a text file, each carriage return/ ine 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 /, an int value will be represented ae 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 conver: imernal representation into external, we can use printf and fprintt Tune Similarly, to convert an extemal representation into internal scani and fscanf can be used. Binary Files: ey binaty file is a file which may contain any type of data, encoded in binary form for computer storage and processing purposes. Like a téxt file, a binary file is a Sltectien of bytes, Note that in Ca byte and a character are equivalent. Shercfore, 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. «= Cplaces no constructs on the file, and it may be read from, or written (0, in any manner the programmer wants. « Binary files store data in the internal representation format. Therefore, an int Bilue will be stored I binary form as 2 or byte value. The same format is used to vtore 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 fil 5.12 Using Files in C To use files in C, we must follow the steps given below. © Declare a file pointer variable * Open the file * Process the file * Close the file 5.12.1 Declaring a File Pointer Variables There can be a number of files on the disk. In orden must specify the name of the file that has to be This is accomplished by using a file pointer variable that points to a structure PILE (defined in stdio.h), The file pointer will then be used in all subsequent operations in the file. to ace particular file, you Maharaja institute of Technology Mysore Dept. of Computer 5 Ts - nd Bons. | EY © scanned with OKEN Scanner Pemerptes of Mograummmg Using © (22POP 1) The syntax for deckaring a file pointer is FILE “file pointer name; For example, af we write FILE “fp; Then, fp is declared as a file pointer An error will be gene pointer wed if you use the filename to access a file rather than the file 5.12.2 Opening a File A file must be first opened before data can be read open a file ociate it with a str ‘The prototype of fopent) can be given as FILE *fopen(const char “file name, const char *mode}; mn it or written to it. In order m, the fopen() function is used. Using the above prototype, the file whose pathname is the stfing pointed to by fle_name is opened in the mode specified using the mode. If successful, fopen() returns ® pointer-to-structure and if it fails, it returns NULL. ‘The Second argument in fopen() is the mode. Mode convey: that will be done with the file Processing are given below. MODE to C the type of processin: he different modes in which a file can be opened for DESCRIPTION : Open a text file for reading. If the stream (file) does not sist then an error will be reported. Open a text file for wi Ifthe stream does : not exist then it is created otherwise if the file already exists, then its contents would be deleted a Append to a text file. if the file does not exist, it is created. » Open a binary file for reading, B indi 7 sequential file in Med binary. By default this will be a 4 format wb Open a binary file for writing ab Append to a bine file Ope! text file for both reading and w positioned at the beginning of the file. When you sp. : rr, you 7 indicate that you'want to read the file before you write to it. Thus the file must already exist we {OPen a text file for both reading and writing, The 1 will be created if it does not exist, and will be truncated if it exist. : Open a text file for both reading and writing, The stream will be positioned at the end of the file content r+b/ bt Open a binary file for read/write jwtb/wb+ Create a binary file for read /write atb/ab+ ary file for read /write Maharaia Institute of Technolaw Mysore, Dae. of Comparer S © scanned with OKEN Scanner ming Using © (22POPI3) ciples of Programan The fopen() can fail to open the specified file under certain conditions that arc listed below a file that is not ready tor usag Opening a file that is specified (o 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; open("Student.DAT", "r"); printf{"\n The file could not be opened’); exit(1}; OR char filename[30]; FILE “fp; gets(filename); = fopen(filename, r+); ULL) printi{"\n The file could not be opened”); exit(1); } 5.12.3 Closing a File Using felose() 7 oaee mai open file, the fclose() function is used which disconnects a fle powntel from a file. After the fclose() has disconnected the fite pointer from the file, the pointer vom tised to access a different file or the same file but in a different mode Tre folosed function not only closes the file but also flushed all the buffers that are maintained for that file rou do not close a file after using it, the system closes it automatically when the program exits. However, since there is limit on the number of files which can be open cree itaneously; the programmer must close a file when it has been used. The prototype of the felose() function can be given a, int felose(FILE *fp); Here, fp is a file pointer which points to the file that has to be closed. The function eee ae an integer value which indicates whether the felose() was successful oF Nek A reuurns ‘turned if the function was successful; and a non-zero value is returned if an error occurred. 5.13 Reading Data From File C provides the following set of functions to read data from a file. + fscanf() + fgets() + fgete() © fread() 5.13.1 fscanf{) The fscan{() is used to read formatted data from the stream. ‘The syntax of the fscani) can be given as, int fscan{{FILE *stream, const char “format, Muharaia Institute of Technology Mysore, Dept. of Co (& scanned with OKEN Scanner Principles of Programming Using G (22POP 13) The fscanf{) is used to read data [rom the stream and store them according to the parameter format into the locations pointed by the additional arguments #include main() FILE *fp; char name[80}; int roll_no: fp = fopen("Student.DAT", "r"); if{fp==NULL) { print{("\n The file could not be opened”); exit(1)}; Printf("\n Enter the name and roll number of the student fscanfistdin, "tos %d", name, &roll_no); /* read from keyboard */ printf{“\n NAME : ‘%s \t ROLL NUMBER = %d", name, roll_no); // READ PROM FILE- Student.DAT fscanf{fp, "%s %d", name, &roll_no}; print{{“\n NAME : %s \t ROLL NUMBER = %d", name, roll_no); felose(fp); 5.13.2 fgets() {gcts() stands for file get string. The fgets() function is used to get a string from 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 cither a new e 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 "\O" character is appended to end the string FILE “fp; char str[80 fp = fopen("Student.DAT’, *r"); if{{p==NULL) t printf{("\n The file could not be opened”); exit(1); ‘tie (fgets(str, 80, fp) != NULL) printf("\n %s", str); printf("\n\n File Read. Now closing the file’ felose(fp); 5.13.3 fgetet The a fuction returns the next character from stream, or EOF if the end of file is reached or if there is an error. The syntax of fgete() can be given as int fgete( FILE *stream ); | fgete returns the character read as an int or return EOF to indicate an error or end of file. parain Institute of Technoloey Mysore. Dept. of Computer Sci (& scanned with OKEN Scanner FILE *fp: char str[80]; int i, chi | fp = fopen("Program.C”, "r"}; iffp==NULL) printfl"\n The file could not be opened}; exit(1)}: // Read 79 characters and store them in str ch = fgetelfpl: for| i=0; (i < 79 ) && ( feof fp) == 0); { str[i] = (char}eh; ch = fgete| stream ); stz[i] = "\0" 0 printf{ “\n %s", str); felose(fp); i to read data from a file. Its syntax can be given as ‘size t size, size_t num, FILE “stream ); .d() function is us int fread{ void “str, ‘The function freadl) reads num number of objects (where each object is size Pete and places them into the array pointed to by str. The data is read from the given input stream. | completion, fread) returns the number of bytes successfully read Will be less than num if a read error or end-of-file is {freadl) will return 0 and the contents of str and the error indicator for the Upon successfu The number of objects encountered. If size or num is 0, State of the stream remain unchanged. In case of error, the stream will be set. ‘The fread() function advances the file position indicator for the stream by the number of bytes read. FILE “fp; char str[11]; fp = fopen("Letter.TXT" if(fp==NULL) 1 printf{"\n The file could not be opened"); exit(1 i fread(str, 1, 10, fp); str[10]= "\0'; printi{"\n First 9 characters of the file are : %s", str); felose(fp); 5.14 Writing Data to Files C provides the following set of functions to read data from a file. Mt: nceand Eng 1 | © scanned with OKEN Scanner faraja Institute of Technology Mysore. Dept. of Computer 5 (ARDS IB He nig © (2APOPLS) Principles of Programm + fprintt) + Ipute) + fwritel) 5.14.1 fprintf) crite formatted output to stream. Its syntax can be given as, intf ( FILE * stream, const char * format, rat is formatted as specified by th: fter the format parameter. the function can have as many The function writes to the specified stream, data format argument ona! arguments mat The pi meter format in the fprinuil is nothing but a C string that contains the texi has to be written on to the stream. FILE “fp; int char name{20]; float salary; fp = fopen|” if{fp==NULL) etails.TXT", "w"}, printf("\n The file could not be opened’ exit(1); for(i=03i<10;i++) | puts("\n Enter your nam ~ gets(name); fflush(stdin); puts("\n Enter your salary scanf{"%f", &salary); fprintf{fp, " (Yed) NAME : [%-10.10s] \t SALARY " %5.2f", i, name, salary); felose(fp); 5.14.2 fputs() The fputs() is used to write a line into a file. The syntax of fputs() can be given as int fputs( const char *str, FILE *stream }; The fputs{) writes the string pointed to by str to the stream pointed to by stream, On successful completion; fputs() returns 0. In case of any error, [puts() returns EOF. #include main() FILE *fp; char feedback{100}; fp = fopen("Comments.TXT", "w"}; printf{"\n The file could not be opened”); exit(1}; print{("\n Kindly give the feedback on tyhis book : nia Institute al Te jalaey Meare (& scanned with OKEN Scanner gets(feedback); fflush(stdin); fputs{feedback, fp}; fclose(fp}; ™ 5.14.3 fputel) The fpute() is used to write a character to the sm int fpute(int ¢, FILE “stream); The fputa) function will write the byte speeified by ¢ (converted to an unsigned char) (0 the output strcam pointed to by siream. Upon successful completion, fpute) will return the value it has written othenvise. in case of error, the function will return EOF an or indicator for the stream will be set #include main() FILE *fp; char feedback{100]; int i fp = fopen(*Comments.TXT", "w if{fp==NULL) print{("\n The file could not be opened exit(1); print{("\n Kindly give the feedback on this boo gets(feedback); forli=Oi

You might also like