0% found this document useful (0 votes)
38 views

Data Structure

Structures in C allow grouping of related data under one name. A structure declaration defines the layout of a structure, while structure variables are used to store actual data. Individual elements within a structure are accessed using the dot operator. File handling in C uses file streams like ifstream for input and ofstream for output. Functions like open(), close(), seekp/seekg() are used to manage files. Files can be opened in text or binary mode, and modes like read, write, append specify file access. Structure and object data can be written to and read from files.

Uploaded by

Patrick Ramos
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
38 views

Data Structure

Structures in C allow grouping of related data under one name. A structure declaration defines the layout of a structure, while structure variables are used to store actual data. Individual elements within a structure are accessed using the dot operator. File handling in C uses file streams like ifstream for input and ofstream for output. Functions like open(), close(), seekp/seekg() are used to manage files. Files can be opened in text or binary mode, and modes like read, write, append specify file access. Structure and object data can be written to and read from files.

Uploaded by

Patrick Ramos
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 15

Structures (Records)

In C, a structure is a collection of variables that are referenced under one name, providing a convenient means of keeping related information together. A structure declaration forms a template that may be used to create structure variables. The variables that make up the structure are called structure elements. Generally, all the elements in the structure are related to each other logically. The following code fragment declares a structure template that defines the name and address fields of a mailing list structure. The keyword struct tells the compiler that a structure is being declared. struct addr{ char name[30]; char street[40]; char city[20]; char state[3]; unsigned long int zip; }; The declaration is terminated by a semicolon because structure declaration is a statement. Also, the structure name addr identifies this particular data structures and its type specifier. The structure name is often referred to as its tag. At this point in the code, no variable has actually been declared. Only the form of the data has been defines. To declare an actual variable with this structure, you would write struct addr addr_info; This declares a structure variable of type addr called addr_info. Or you can include it directly from the structure you made. struct addr{ char name[30]; char street[40]; char city[20]; char state[3]; unsigned long int zip; } addr_info; The structure tag name is the name of the structure not the variable name. The structure variables are a comma separated list of variable names. !emember, either structure tag name or structure variables are optional, but not both. !eferencing "tructure #lements

Individual structure elements are referenced by using the . usually the !dot"# operator. $or e%ample, the following code assigns the &ip code '()*+ to the &ip field of the structure variable addr_info declared earlier addr_info.zip $ %234&, The general form if structure-name.element-name.

File Handling
In C//, file input0output operations are implemented through a component header file called fstream.h. The fstream library predefines a set of operations for handling file related input and output. It defines certain classes that help perform file input and output. The important stream classes re1uired for file I0O are. ifstream' is re1uired for input from a file 2reading from a file3. Its member function open( ) associates the stream with a specified file in an input mode. $or e%ample, if a file called xyz.dat is re1uired to be opened for reading, the following statements can be sued. ifstream readfile, readfile.open24%y&.dat53, ofstream' is re1uired for output to a file 2writing to a file3. Its member function open( ) associates the stream with a specified file in an output mode. $or e%ample, if a file called xyz.dat is re1uired to be opened for writing, the following statements can be sued. ofstream writefile, writefile.open24%y&.dat53,

fstream' can be used for simultaneous input from and output to a file. The member functions commonly used are. 1. 2. 3. 4. %. &. '. open close close all seekg seekp tellg tellp : associates the stream with a specified file. : close the stream. : closes all open streams. : Used with inp t file (ifstream). !eeks "yte no. in a data file. #x. fileo t.seekg(3$) will goto "yte n m"er 3$. . !ame as seekg " t sed with o tp t file (ofstream). : ret rns c rrent get position. : ret rn c rrent p t position.

File Mode Constants


$ilemode describes how a file is to be used. to read from it, to write to it, to append to it and so on. 6hen a stream is associated with a file, either by initiali&ing a file stream ob7ect with a file name or by using the open( ) method, a second argument specifying the file mode can be provided. fstream newfile, newfile.open24%y&.dat5, ios..out3, 8ultiple filemodes can also be specified with fstream. fstream newfile, newfile.open24%y&.dat5, ios..in 9 ios..out3,

File Mode Constants


(onstant ios''in ios''out ios''app ios''ate ios''trunc ios''nocreate ios''noreplace )hat it means Opens file for !eading O:;<. Open file for 6riting O:;<. =revious contents are discarded. Open the file for Appending. :ew records are added to the file. Open the file and seeks the end>of>file upon opening. ?estroys the contents of a pre e%isting file by the same name. ?oes not open a new file if a file with the same name does not already e%ist. ?oes not open a new file if a file with the same name already e%ist.

ios''*inary

?ata files can be opened in Te%t mode or @inary 8ode. @y default files are opened in Te%t 8ode. 6hen a file is opened is Te%t 8ode, various character translation may take place such as carriage>return 2enter3 into newline. Aowever, no such character translation takes place in @inary 8ode. Any file can be opened in te%t 8ode or @inary 8ode. The only difference is the occurrence of character translation in Te%t 8ode.

File Pointers & Random Access


see+g see+p ios''*eg ios''cur ios''end Bsed with input file 2ifstream3. "eeks byte no. in a data file. #%. fileout.seekg2)C3 will goto byte number )C. "ame as seekg but used with output file 2ofstream3. !efers to beginning of file. !efers to current position in the file. !efers to end of the file. #%. 2'3 fileinput.seekg2)C,ios..beg3 goto byte number )C from the beginning of the file. 2(3 fileinput.seekg2>(,ios..cur3 back up ( bytes from current position. 2)3 fileinput.seekg2C,ios..end3 goto the end of file. 2*3 fileinput.seekg2>+,ios..end3 backup + bytes from end of file.

Reading and Writing Strings to Disks and Detecting End of File


,ample -rogram' ./ 0123%.(-,e4uential 0ile 5andling -rogram to create a single se4uential file and then display its content /. 6include 7fstream.h8 ..needed for file handling operations 6include 7conio.h8 main # { ofstream fileout; ..open output file employee for append fileout.open 9employee.dat9#; char name[30]; char ch; float salary;

char ans$:y:; clrscr #; ;hile ans$$:<:==ans$$:y:# { cout77endl7793mployee >ame 9; cin.get name?30#; ..read string cout77endl779,alary 9; cin88salary; cin.get ch#; ..empty *uffer enter character# ..;rite to file fileout77name77:@n:77salary77:@n:; cout779@n3nter Aore Becord [<.>] 9; ans$getch #; } fileout.close #; ..close the file ifstream fileinput; ..open employee.dat for reading records fileinput.open 9employee.dat9#; fileinput.see+g 0#; ;hile Cfileinput.eof ##; ..3D0 detects end of file { fileinput.get name?30#; ..read employee name fileinput.get ch#; ..read the eEtra character fileinput88salary; ..read salary fileinput.get ch#; ..read the eEtra character cout77endl7793mployee:s >ame 977name77endl; cout7793mployee:s ,alary 977salary77endl; } fileinput.close #; ..close file }

Reading and Writing Structure to Disks


./ 01232.(-)riting structure to file Fisplay structure from file /. 6include 7fstream.h8 6include 7conio.h8 6include 7stdio.h8 struct student { char name[2&]; char roll[&];

..0or gets #; ..Feclare a ,tructure

int total; }; main # { char fname[%&]; ..0or Dutput 0ilename int num*er; ..0or >um*er of ,tudents student srec; ..Feclare ,tructure Garia*le ofstream outfile; clrscr #; cout7793nter the name of the file to *e created 9; cin88fname; outfile.open fname#; ..Dpen the filename in output mode if Coutfile# ..(hec+out for 0ile 3rrors { cout77endl7793BBDBCCC (annot Dpen 0ile9; return %; } cout77endl7793nter the num*er of students in the class 9; cin88num*er; for int i$0;i7num*er;iHH# ..Iet Becords { ..Bead the ,tructure from Jey*oard cout779>ame 9; gets srec.name#; cout779Boll 9; gets srec.roll#; cout779Kotal 9; cin88srec.total; ..)rite to 0ile outfile.;rite char /# Lsrec?sizeof srec##; } ..(lose the 0ile outfile.close #; ..Fisplay Mll the Becords in the 0ile ifstream infile; infile.open fname#; infile.see+g 0#; ;hile Cinfile.eof ## { infile.read char /# Lsrec?sizeof srec##; cout77endl77endl779>ame 977srec.name; cout77endl779Boll 977srec.roll; cout77endl779Kotal 977srec.total; } infile.close #;

..,ee+ Neginning of 0ile

..Fisplay Becords

..(lose the 0ile

return 0#; }

Reading and Writing Objects to Disks


..01234.(-..-rogram to create a file of o*Oects 6include7fstream.h8 6include7conio.h8 class student { protected' int rl; ..roll num*er char name[30]; ..name char cl[3]; ..class pu*lic' Goid input # { char ch; cout779@n3nter Boll >o. 9; cin88rl; cin.get ch#; ..empty *uffer enter character# cout779@n3nter >ame 9; cin.getline name?30#; cout779@n3nter (lass 9; cin.getline cl?3#; } Goid display # { cout779@nBoll >o ' 977rl; cout779@n>ame ' 977name; cout779@n(lass ' 977cl; } }; Goid main # { student std; ..o*Oect declaration fstream file; ..file decalaration char choice; file.open 9student.dat9?ios''app=ios''out=ios''in#; ..open file

clrscr #; do { cout779@n 3nter 1nformation '9; std.input #; ..call function input file.;rite char/# Lstd? sizeof std##;..;rite to file cout779@n3nter Aore[y.n]P 9; ..as+ for more info. cin88choice; };hile choice$$:<:==choice$$:y:#; ..file.close #; ..file.open 9student.dat9?ios''app=ios''out?ios''in#; ..open file file.see+g 0#; ..reset the file:s current pointer to starting file.read char /# Lstd? sizeof std##; ..read from file cout779@n,KQF3>K 1>0DBAMK1D> '9; ..display students: information ;hile Cfile.eof ## { std.display #; ..call function display cout77endl; file.read char /# Lstd? sizeof std##; ..read from file } file.close #; getch #; }

(haracter ,tring 0unctions in iostream 2i*rary


0unction L -urpose

get ch#
#%tracts one character from the stream and places it into the variable named ch.

3Eample char one, cin.get2one3,

get string? maE#


#%tracts characters from the stream and places them into variable string until either ma%>' characters have been read or a newline 2Dn3 is found or an end of file is reached. The string is null>terminated by get23, If the newline is found, it is not e%tracted and remains in the input stream until the ne%t read operation.

char nameE)CF, cin.get2name,)C3, 0G reads upto (H characters and adds terminating null 2DC3. The Dn remains in the input stream. G0

get string? maE? delimiter#

char nameE)CF,

cin.get2name,)C,I%I3, #%tracts characters from the stream and places them into variable string until either ma%>' characters have been read, the delimiter character has been found, or the end of file is reached. The string is null>terminated by get23, The delimiter character is left in the stream until the ne%t read. 0G reads upto (H characters or until it sees an % in the stream and adds terminating null 2DC3. The Dn or delimiter remains in the input stream. G0 char nameE)CF, cin.getline2name,)C3, 0G reads upto (H characters and adds terminating null 2DC3. The Dn is removed from the input stream. G0

getline string? maE#


#%tracts characters from the stream and places them into variable string until either ma%>' characters have been read, a newline 2Dn3 is found or an end of file is reached. The string is null>terminated by getline23, If a newline is encountered, it is e%tracted from the stream but not put into the string.

getline string? maE? delimiter#


#%tracts characters from the stream and places them into variable string until either ma%>' characters have been read, the delimiter character has been found, or the end of file is reached. The string is null>terminated by get23, If the delimiter character has been found, it is e%tracted from the stream and not put in the string.

char nameE)CF, cin.getline2name,)C,I%I3, 0G reads upto (H characters or until it sees an % in the stream and then adds terminating null 2DC3. The Dn or delimiter is removed from the input stream. G0

..0123&.(-..-rogram to create a file of o*Oects

6include 7conio.h8 6include 7fstream.h8 6include 7stdio.h8 6include 7string.h8 6include 7process.h8 6include 7io.h8 int count$0;

..for eEit ..for flielength #

class Kelephone { priGate' char name[30];

char address[30]; char phone[%0]; int unit; pu*lic' Goid getdata Goid#; Goid display Goid#; Goid modify Goid#; }; Goid Kelephone''getdata Goid# { char ch; clrscr #; gotoEy %&?%0#; cout779Nharat ,anchar >igam 2imited R 1nput Becord@n9; gotoEy %S?%2#; cout779Becord 6977 HHcount#77endl; gotoEy %?%4#; cout779@n3nter >ame ' 9; cin.getline name?30#; cout779@n3nter Mddress ' 9; cin.getline address?30#; cout779@n3nter -hone >o. ' 9; cin.getline phone?30#; cout779@n3nter Qnit ' 9; cin88unit; } Goid Kelephone''display Goid# { clrscr #; gotoEy %&?%0#; cout779Nharat ,anchar >igam 2imited R Fisplay Becord@n9; gotoEy %?%2#; cout779@n>ame ' 977name; cout779@nMddress ' 977address; cout779@n-hone >o. ' 977phone; cout779@nQnit ' 977unit; }

Goid Kelephone''modify Goid# { char tname[30]; char taddress[30]; char tphone[%0]; int tunit; clrscr #; gotoEy %&?%0#; cout779Nharat ,anchar >igam 2imited R Aodify Becord@n9; gotoEy %S?%2#; cout779@n(urrent Fetails@n9; gotoEy %?%2#; cout779@n>ame ' 977name; cout779@nMddress ' 977address; cout779@n-hone >o. ' 977phone; cout779@nQnit ' 977unit; cout779@n3nter >e; Fetails 977endl; cout779@n3nter >ame ' 9; cin.getline tname?30#; cout779@n3nter Mddress ' 9; cin.getline taddress?30#; cout779@n3nter -hone >o. ' 9; cin.getline tphone?30#; cout779@n3nter Qnit ' 9; cin88tunit; strcpy name?tname#; strcpy address?taddress#; strcpy phone?tphone#; unit$tunit; } Goid main Goid# { clrscr #; Kelephone tel; fstream fileout; fileout.open 9Kel.dat9?ios''in=ios''out=ios''app#;

if Cfileout# { cout779(annot Dpen 0ile9; eEit 0#; } int choice; int mrec$0; int offset$0; char ans?ch; do { clrscr #; cout779@n@nNharat ,anchar >igam 2imited9; cout779@n@n@t@tAain Aenu 9; cout779@n@n@t%. Mdd Becord 9; cout779@n@t2. Aodify Becord 9; cout779@n@t3. Fisplay Becord 9; cout779@n@t4. 3Eit 9; cout779@n@n@3nter <our (hoice [%R4] 9; cin88choice; cin.get ch#; ..empty *uffer enter character# s;itch choice# { case %' tel.getdata #; mrec$count; offset$ mrecR%#/sizeof Kelephone##; fileout.see+p offset?ios''*eg#; fileout.;rite char /#Ltel?sizeof Kelephone##; *rea+; case 2' if Ccount# { cout779>o records found.@n9; cout779@n-ress a +ey to continue...9; getch #; *rea+; } cout779@nAodify ;hich recordP 6 9; cin88mrec; cin.get ch#; ..empty *uffer enter character# if mrec8count# { cout7791nGalid record no.@n9; cout779@n-ress a +ey to continue...9;

getch #; *rea+; } else { offset$ mrecR%#/sizeof Kelephone##; fileout.see+g offset?ios''*eg#; fileout.read char /#Ltel?sizeof Kelephone##; tel.display #; cout779@nAodify this record [y.n] 9; cin88ans; cin.get ch#; ..empty *uffer enter character# if ans$$:<: == ans$$:y:# { tel.modify #; fileout.see+p offset?ios''*eg#; fileout.;rite char /#Ltel?sizeof Kelephone##; cout779@nBecord Aodified9; cout779@n-ress any +ey to continue...9; getch #; } *rea+; } case 3' if Ccount# { cout779>o records found.@n9; cout779@n-ress a +ey to continue...9; getch #; *rea+; } fileout.see+g 0#; fileout.read char /#Ltel?sizeof Kelephone##; cout779@nB3(D-BF >D. 69; tel.display #; do { fileout.read char /#Ltel?sizeof Kelephone##; cout779@n-ress a +ey to display neEt record9; getch #; tel.display #; };hile Cfileout.eof ##; cout779@n-ress any +ey to continue...9; getch #;

*rea+; case 4' [email protected]; cout779@n-ress a +ey to continue...9; getch #; eEit 0#; default'cout779@n@n@a@a@a1nGalid choice9; *rea+; } };hile choice8$% LL choice 7$4#; fileout.close #; }

You might also like