Sunteți pe pagina 1din 48

1.

STUDY OF ASSEMBLERS

Assembler is a system program which converts a program written in assembly language into machine language. Assembly language is a special language in which we use special mnemonic symbols for each instruction . It takes input of an assembly language program known as source program and converts it into an equivalent machine language program which is our object program. General design procedure 1. specify the problem 2. specify data structure 3. define format of DS 4. specific algorithm 5. look for modularity, i.e. capability on one program to be subdivided into several sub programs. 6. Repeat step 1 to 5 until our problem is resolved . Passes in assembler There are two passes in assembler. (1) Pass1 & (2) Pass2

PASS1
The purpose of pass1 is to define symbols and literals . following are the steps included in pass1. 1. 2. 3. 4. 5. determine length of machine imstruction .it is known as MOTGET1. Keep track of location counter . rememeber values of symbols until pass2. it is known as STSTO. process some pseudo ops like EQU, DS . it is known as POTGET!. remember literals . it is known as LITSTO(literal store).

PASS 2
The purpose of pass2 is to generate object program. Following are steps included in 1. 2. 3. 4. look up value of symbols . it is known as STGET(single table get). Generate instructions . it is known as MOTGET. Generate data for DS(define storage), DC(define constant) and literals. Process of pseudo ops .it is known as POTGET2. pass2.

PASS ONE OF THE TWO PASS ASSEMBLER

PASS TWO OF THE TWO PASS ASSEMBLER

2. STUDY OF LEXICAL & SYNTAX ANALYSIS


LEXICAL ANALYSIS:
It is a first phase of the compiler. In this phase compiler separates characters of source language into groups that logical belongs together. These groups are tokens. This part of compiler is known as lexical analyzer or scanner. On order to perform lexical analyzer must know what are the tokens of the language to implemented .i.e. It must we know identifiers ,keywords , operators or punctuations symbols etc. so that when it scan the source program it will be able to return a suitable tokens.

SYNTAX ANALYSIS:
It is also known as passing and the program used for this purpose is known as parser. A parser obtains a string of tokens from the lexical analyzer and verify whether the string is valid instruct of the source language .for this purpose of parser either attempts to derive the string of tokens W from the start symbol S or attempts to reduce W to start symbol S of the grammar.

TWO TYPES OF PARSING:


1.) TOP-DOWN PARSING 2.) BOTTOM-UP PARSING

LEFT MOST DERIVATION:


If while generating a language from a given grammar. We dont scan the next variable until the leftmost variable scanned as leftmost derivation.

RIGHT MOST DERIVATION:


While generating a language from a given grammar we dont scan the next variable until the rightmost variable is scanned is known as rightmost derivation.

1. TOP-DOWN PARSING:
In an attempt to generate a leftmost derivation of a given grammar. The basic idea is to parse our program starting from top and moving bottom. It means until or unless our first line is not error free or correct according to syntax .we can not move on to next line. E.g. LL(K) grammar context free grammars called LL(K) from left to right scan producing a left most derivation with K symbols look ahead if we can always make a correct decision by checking at most the first K symbols of W. Let this is our context free grammar. P is S -> A+B-C

A -> b B C -> c -> d

2. BOTTOM UP PARSING:

While parsing our program if we are moving starting from bottom and going to top of our source program then it is known as bottom up parsing. The basic idea is unless or until the last line of our source program is not error free or correct according to the syntax. We can not move to the next line and it is equivalent to finding the right most derivation of any grammar.e.g. LR (K) grammar: while finding a rightmost derivation of any grammar by looking ahead K symbols we determine which production to use then is known as LR (K) grammar. It equivalent to finding the right most derivation of the grammar. Let this is our given grammar.

3. INSTRUCTION SET OF 8085 MICROPROCESSOR


INTRODUCTION:
An instruction is a command given to the computer to perform a specified operation on given data. These instructions are classified into following groups: 1. Data Transfer Group 2. Arithmetic Group 3. Logical Group 4. Branch Control 5. I/O and machine Control

Data Transfer Group: Instructions which are used to transfer data from one register

to another register, from memory to register or register to memory. Various commands are: 1. MOV r1, r2: Move data; Move the content of one register to another. 2. MOV r, M: Move the content of memory to register. 3. MOV M, r: Move the content of register to memory. 4. MVI r, data: Move immediate data register. 5. LXI rp, data 16: Load registers pair immediate. 6. LDA addr: Load accumulator direct. 7. STA addr: Store accumulator direct. 8. LHLD addr: Load H-L pair direct. 9. SHLD addr: Store H-L pair direct. 10. XCHG: Exchange the contents of H-L with D-E pair.
Arithmetic Group: The instructions of this group perform arithmetic operations such

as addition, subtraction, increment, decrement of the contents of the register or memory. Various commands are: 1. ADD r: Add register to accumulator. 2. ADD M: Add memory to accumulator. 3. ADC r: Add register with carry to accumulator. 4. ADC M: Add memory with carry to accumulator. 5. ADI data: Add immediate data to accumulator. 6. DAD rp: Add register pair to accumulator.

7. SUB r: Subtract register from accumulator. 8. SUB M: Subtract memory from accumulator. 9. SBI data: Subtract immediate data from accumulator with borrow. 10. INR r: Increment registers content. 11. INR M: Increment memory content. 12. DCR r: Decrement registers content.

Logical Group: The instructions under this group perform logical operations such as

AND, OR, COMPARE, ROTATE etc.Various commands are: 1. ANA r: AND register with accumulator. 2. ANA M: AND memory with accumulator. 3. ANI data: AND immediate data with accumulator. 4. ORA r: OR register with accumulator. 5. ORA M: OR memory with accumulator. 6. XRA r: EXCLUSIVE OR register with accumulator. 7. XRA M: EXCLUSIVE-OR memory with accumulator. 8. CMA: Complement accumulator. 9. CMC: Complement the carry status. 10. STC: Set carry status. 11. CPI data: Compare immediate data with accumulator. 12. RLC: Rotate accumulator left. 13. RAL: Rotate accumulator left through carry.

14. RAR: Rotate accumulator right through carry.

Branch Control Group: This group includes the instructions for conditional and unconditional jump, subroutine call and return and restart. Various Commands are: 1. 2. JMP addr (label): unconditional Jump: jump to the instruction specified by the Conditional jump addr: after the execution of the conditional jump instruction the

address. program jumps to the instruction specified by the address. If the specified condition is fulfilled. 3. 4. 5. CALL addr: Unconditional call; Call the subroutine identify by the address. RET: Return from subroutine. RST n: Restart: It is a one word CALL instruction.

Stack and I/O, Machine Control Group: This group includes the instructions
from I/O ports, Stack and machine control. Various commands are:

1. IN Port addr: Input to accumulator from I/O port. 2. OUT Port addr: Output from accumulator to I/O port. 3. PUSH PSW: Push processor status word. 4. PUSH rp: Push the content of register pair to Stack. 5. POP rp: Pop the content of register pair to Stack. 6. HLT: Halt 7. EI: Enable interrupts. 8. DI: Disable interrupts.

9. SIM: Set interrupt mask. 10. RIM: Read interrupt mask. 11. NOP: No operation.

4. STUDY OF COMPILER AND ITS VARIOUS PHASES

COMPILER:
Compiler is a system program which converts a program written in high level language into machine language. The high level language program given as input is known as source program and machine equivalent is known as object program. The functionality of compiler is divided into seven phases: 1. Lexical Phase 2. Syntax Phase

3. Interpretation Phase 5. Storage Assignment 7. Code Generation

4. Optimisation 6. Assembly Phase

Phases of a compiler 1. LEXICAL PHASE:


Action of parsing source program into proper classes is the task of lexical analyzer. The program is scanned and separated into basic elements known as tokens. The basic elements like identifier, literals are placed into tables as other phases recognize the use and meaning of elements further information is entered into these tables like data types, length, storage classes etc.

2.

SYNTAX PHASE:

Compiler interprets the meaning of the constant syntax analyzer is also known as parsing. The basic function of the syntax phase is to recognize the major constructs of language and

to calculate the appropriate action routines that will generate the intermediate form or matrix for these constructs. 3. INTERPRETATION PHASE: Once the program is correct according to syntax, the compiler generates a intermediate code , in this phase , the intermediate code is compiler directed .This intermediate co ode may be in form of parse tree ,postfix notation and three address code .

4. OPTIMISATION:
Any program is set to be optimized, if it is consumes less memory and the compiler time is fast. The code optimizer receives intermediate code and optimize them considering the like memory, execution time and other. This phase removes the redundant code.

5. STORAGE ASSIGNMENT:
It is the process of allocating memory to various resources. The memory can be allocated to various literals, storage, symbols, machine-OP etc. also the processing environment may need some memory. All these memory allocation are performed by compiler in this phase.

6.

CODE GENERATION:

It is the last phase of compiler. This phase receives optimized intermediate code and generates the code for execution. This code generated generally will be relocatable machine code or assembly code. This phase generates the executed code. It receives the input from intermediate code generator from code optimizer in case of optimizing compilers. The input to code generator must be error free, it must have undergone lexical analysis, syntax and other intermediate phases. The target program may be in the form of 1. 2. 3. Assembly language Relocate machine code Absolute machine language

The absolute machine code is 1 which is ready to be executed. It is Linker and loaded by the loader, thus making it ready for execution.

5. DEBUGGING IN C++ ENVIRONMENT


Locating and removing errors is known as debugging. A debugger is a system program which locates bugs and removes them.

Debugging Procedure:
1. 2. 3. 4. Type any program in the given language. Compile it. Look for errors. Remove errors and recompile the program.

5.

Repeat steps 3 & 4 until our program becomes error free.

CASE STUDY: Debugging in C++ environment


We can divide the debugging procedure in C++ in two main categories: 1. 2. Single-step control debugging Break point control debugging

1. Single step control debugging:


There are three main methods of debugging in C++ environment under this category: a) b) c) Single line control Watch window Procedure control

a) Single line control: After compilation if there are any errors in our program then pressing

the F7 key will check our program in a single line control. Where there is any error or bug in any line then that particular line is skipped and the control is transferred to the next adjacent line. Watch window: After pressing F7 key, if we press Ctrl+F7 then a watch window will be displayed on the screen. The user has to type a variable in the add watch window and the value of that variable will be displayed.
b) Procedure control: This debugging technique is used if our program is very large and it is

divided into several sub-procedures. Simply pressing F8 key will result our program to be compiled on procedure basis.

2. Break point control debugging:

The break point method as the name employs allows the user to set break points in the program in order to check the contents of registers, memories and other programming entities like variables etc. In fact the break point allows the user to halt the execution of the program at that break point. Then the user can examine the intermediate results or contents of various registers, memories, variables, addresses and I/O ports. The break point can be inserted at any particular position in our program by the user himself

6. STUDY OF EDITORS AND TYPES OF EDITORS


Editor is a system program that interfaces a program with the entity that generates a data (originator). It also interfaces the results of the program with the entity that consumes them (consumer).There are a few steps in program development: 1) 2) 3) 4) 5) program design, coding and documentation preparation of programs in machine readable form program translation, linking and coding program testing an d debugging performance enhancement of the program

6)

reforming the data or the result of the program

Design and Coding:


There are two methods for design and coding:

Program Generator:

It generates a program which performs a set of functions described in its specifications. The user has to only specify the functions to be performed and not how to perform them.

Program Environment:

It supports programming by including awareness of the programming language syntax and semantics in the language editor

Program entry and editing:


The soft tools used are text editors. Editor function in two modes 1. Command Mode It accepts the user commands specifying the editing function to be performed. 2. Data Mode The user keys in the text to be added to the files.

Testing and Debugging:

Various task to be performed here are selection of test data for the programs, analysis of test results to detect errors if any and debugging. Software tools used to implement these steps are: 1. Test data generators

They help the user to select test data for the program. Test data is a set of input values that satisfy the conditions required for correct flow of data. 2. Automated test drivers

Here the program correctness is verified by subjecting is to a standard set of tests after every modification. This is called regression testing.

3.

Debug Monitors

It is a software which provides debugging support for a program. It executes the program been debugged under its control. It also enables the monitor to perform dynamically specified debugging actions. They perform the following facilities for dynamic debugging: a) b) c) d) e) Setting break points in a program. Initiate a debug conversation when the control reaches the break point. Display the value of variables. Assign new values to variables. Testing user defined assertions involving program variables.

Enhancement of program performance:


Program efficiency depends on efficiency of the algorithm and efficiency of the coding. Editor comes in different forms: 1) 2) 3) 4) 5)
6)

Line editor Stream editor Screen editor Word processors Structure editor Graphical editors

LINE EDITOR
The scope of edit operations on line editor is limited to line of text. The line is designated: a) Positionally b) By specifying a serial number in text Contextually a) By specifying a unique character string in it.

The primary advantage of line editors is there simplicity.

STREAM EDITOR
A stream editor views the entire text as a stream of character this permits edit operations to cross line boundaries. Stream editors typically supports character oriented , line oriented and context oriented modes. The current pointer can be manipulated using all these modes.

SCREEN EDITORS
Line or stream editors do not display the text in manner it would appear if printed. Screen editor uses the What-you-see-is-what-you-get principle. The editor displays a screen full of text at a time the user can move the cursor over the screen, position it at a point where we want to perform. Some editing proceeds with the editing directly. Thus it is possible to see the effect of an edit operation on screen.

WORD PROCESSOR
Word processors are document editors with additional features to produce well formatted hard copy output. Essential features of word processor are command for moving, merging of texts and searching and replacing of words. Many word processors supports spell check options with the adventure of personal computers. Word processors have seen wide spread use among authors, office personal and computer professional.

STRUCTURE EDITOR
A structure editor incorporate an awareness of the structure of a document .This is useful in browsing through a document

CASE STUDY OF MS-WORD, DOS EDITOR , VI EDITOR

DOS EDITOR Introduction

1. 2. 3. 4. 5.

How to start the Dos editor. How to create a file in the editor. What is a batch file. How to create a batch file. How to execute a batch file.

What is DOS Editor?


The DOS Editor is used to display , create , print , and modify files. The DOS Editor looks a little like a word process

EDIT How do you access the DOS Editor?


Type EDIT at the command prompt and press the ENTER key. To name a file before starting type EDIT and the filename. Press the ENTER key.

Why do you want to use DOS Editor?


You use the DOS Editor to create Batch Files.

What are Batch Files?


A batch file contains a series of DOS commands. Batch files have a .bat extension.

What do you do with a batch file?


Batch file are like icons on a toolbar. They simplify your life. Imagine if you had a room full of computers. You wanted ti perform the same function on each of the computers. You have a few options. Sit at each computer and perform the function. Build a batch file. Execute the batch file. Have time to relax before your next project.

How do you run or execute a batch file?


Type the batch file name. There is no need to type the .bat extension.

How do you stop or pause a batch file?


Interrupt batch file: CTRL+S Cancel batch fil

What are some special batch file commands and what is the purpose of each? ECHO OFF
This turns off all DOS commands after the ECHO OFF command. If a DOS command has related questions you will see the questions. The only thing you do not see are the DOS commands. @ ECHO OFF This turn off all DOS commands including the ECHO OFF command .

Now , do you understand the difference between ECHO OFF and @ECHO OFF?
ECHO OFF - You see ECHO OFF @ECHO OFF - You dont see ECHO OFF ECHO. This create a blank line. ECHO This display a message on a monitor. PAUSE This pause your computer until you press any key.

VI EDITOR INTRODUCTION
The VI editor is a screen based editor used by many Unix users . The VI editor has a powerful feature to aid programmer, but many beginning users avoid using VI because the different features overwhelm them. This tutorial is written to help beginning users get accustomed to using the VI editor , but also contains section relevant to regular users of VI as well. Examples are provided , and the best way to learn is to try these examples as well. Theres no better way than to experience things yourself.

Starting the VI Editor


The VI editor lets a user create new files or edit existing files . The command to start the VI editor is vi, followed by the file name. For example to edit a file called temporary, you would type vi temporary and then return . You can start VI without a filename , but when you want to save your work , you will have to save your work , you will have to tell VI which filename to save it into later

The Two Modes of VI


The first thing most users learn about the VI editor is that it has two modes : command and insert . The command mode allows the entry of commands to manipulate text . these commands are usually one or two characters long, and can be entered with few keystrokes. The insert mode puts anything typed on the keyboard into the current file. into insert mode . The most commonly used commands to get into insert mode are a and i . These VI starts out in command mode. There are several commands that put the VI editor two commands are described below . Once you are in insert mode , you get out of it by hitting the escape key . If your terminal does not have an escape key , ^ [ should work(control-)]. You can hit escape two times in a row and VI would definitely be in command mode . Hitting escape while you are already in command mode doesnt take the editor out of command mode . It may beep to tell you that you are already in that mode.

7. C++ PROGRAMS
i.

Write a program to generate lexical & syntax analyzer for a declaration statement .

#include<iostream.h>

#include<conio.h> #include<string.h> #include<process.h> #include<stdio.h> void main() {clrscr(); char b[20],c1[20],c2[20],c3[20]; int i,j=0,l=0,first,second,m=0,c=0; cout<<"enter a string"<<endl; gets(b); for(i=0;b[i]!='\0';i++) {if(b[i]==' ') {c++;}} if(c!=2) {cout<<"wrong"<<endl; getch(); exit(0);} cout<<endl; for(i=0;b[i]!=' ';i++) {c1[j]=b[i]; j++;} c1[j]='\0'; cout<<"c1="<<c1; first=i; for(i=first+1;b[i]!=' ';i++) {c2[l]=b[i]; l++; }

c2[l]='\0'; cout<<endl<<"c2="<<c2; second=i; for(i=second+1;b[i]!='\0';i++) {c3[m]=b[i]; m++;} c 3[m]='\0'; cout<<endl<<"c3="<<c3<<endl; if(strcmp(c3,";")!=0) {cout<<"invalid statement"<<endl;} if(strcmp(c1,"int")==0) {cout<<"datatype is integer";} else if(strcmp(c1,"ch")==0) {cout<<"datatype is character";} else if(strcmp(c1,"float")==0) {cout<<"datatype is float";} else {cout<<"datatype is wrong"; }getch();}

Output:

ii.

Write a program to generate various data structures of lexical analysis phase .

#include<iostream.h> #include<conio.h> #include<string.h> #include<stdio.h> #include<process.h> void main() { clrscr(); int n,a,x=0; int lin=0,ch=0; int tc=0,ic=0,lc=0,uc=0,symb=0; int i=0,l=0; char terminal[15][15],identifier[15][15],literal[15][15],usymbol[15][15],symbinfo[15][15]; char str[20][20]; cout<<"Enter no of statements of source program "<<endl; cin>>n; for(a=0;a<n;a++) { gets(str[a]);} cout<<endl; for(lin=0;lin<n;lin++) // outer loop { ch=0; while(str[lin][ch]!=' ') // inner loops start here

{ terminal[tc][i]=str[lin][ch]; usymbol[uc][i]=str[lin][ch]; ch++; i++; } strcpy(symbinfo[uc],"Terminal"); terminal[tc][i]='\0'; usymbol[uc][i]='\0'; while(x<uc) { if(strcmp(usymbol[uc],usymbol[x])==0) { uc--; break; } x++; } x=0; while(x<tc) { if(strcmp(terminal[tc],terminal[x])==0) { tc--; break; } x++;

} x=0; ch++; i=0; tc++; uc++; while(str[lin][ch]!=' ') { identifier[ic][i]=str[lin][ch]; usymbol[uc][i]=str[lin][ch]; ch++; i++; } strcpy(symbinfo[uc],"Identifier"); identifier[ic][i]='\0'; usymbol[uc][i]='\0'; while(x<ic) { if(strcmp(identifier[lc],identifier[x])==0) { ic--; break; } x++; } x=0; while(x<uc) // this checks the duplicacy of symbol table

{ if(strcmp(usymbol[uc],usymbol[x])==0) { uc--; break; } x++; } x=0; i=0; ic++; uc++; ch++; while(str[lin][ch]!=' ') { terminal[tc][i]=str[lin][ch]; usymbol[uc][i]=str[lin][ch]; i++; ch++; } strcpy(symbinfo[uc],"Terminal"); terminal[tc][i]='\0'; usymbol[uc][i]='\0'; while(x<tc) { if(strcmp(terminal[tc],terminal[x])==0) {

tc--; break; } x++; } x=0; while(x<uc) { if(strcmp(usymbol[uc],usymbol[x])==0) { uc--; break; } x++; } x=0;

ch++; tc++; uc++; i=0; while(str[lin][ch]!=' ') { literal[lc][i]=str[lin][ch]; usymbol[uc][i]=str[lin][ch]; ch++; i++;

} strcpy(symbinfo[uc],"Literal"); literal[lc][i]='\0'; usymbol[uc][i]='\0'; while(x<lc) { if(strcmp(literal[lc],literal[x])==0) { lc--; break; } x++; } x=0; while(x<uc) { if(strcmp(usymbol[uc],usymbol[x])==0) { uc--; break; } x++; } x=0; i=0; lc++; uc++;

ch++; while(str[lin][ch]!='\0') { terminal[tc][i]=str[lin][ch]; usymbol[uc][i]=str[lin][ch]; ch++; i++; } strcpy(symbinfo[uc],"Terminal"); terminal[tc][i]='\0'; usymbol[uc][i]='\0'; while(x<tc) { if(strcmp(terminal[tc],terminal[x])==0) { tc--; break; } x++; } x=0; while(x<uc) { if(strcmp(usymbol[uc],usymbol[x])==0) { uc--; break;

} x++; } x=0; i=0; tc++; uc++; } cout<<"terminals table "<<endl; for(l=0;l<tc;l++) {cout<<l<<" "; puts(terminal[l]); cout<<endl; } cout<<"Identifier table "<<endl; for(l=0;l<ic;l++) 4{cout<<l<<" "; puts(identifier[l]); cout<<endl; } cout<<"Literal table "<<endl; for(l=0;l<lc;l++) {cout<<l<<" "; puts(literal[l]); cout<<endl; } cout<<"uniform symbol "<<endl;

for(l=0;l<uc;l++) {cout<<l<<" "; cout<<usymbol[l]<<" "<<symbinfo[l]; cout<<endl; } getch(); }

Output:

iii.

Write a program to perform different set operations i.e. union , intersection etc. .

#include<iostream.h> #include<conio.h> void main() { clrscr(); int a[20],b[20],c[40],j,n,m,k,choice; int i; cout<<"Enter no of elements of a"; cin>>n; cout<<"\nEnter "; for(i=0;i<n;i++) { cin>>a[i]; } cout<<"Enter no of elements of b"; cin>>m; cout<<"\nEnter "; for(i=0;i<m;i++) { cin>>b[i]; } while(1) {cout<<"\n\t\tMENU"; cout<<"\n\t\t1.inter"; cout<<"\n\t\t2.union"; int ch; cout<<"\nEnter choice"; cin>>ch;

if(ch==2) { for(i=0;i<n;i++) { c[i]=a[i]; } int k=n; for(i=0;i<m;i++) { for(j=0;j<n+i;j++) { if(c[j]==b[i]) break;

} if(j==n+i) { c[k]=b[i]; k++; } } cout<<"\nUNION "; for(i=0;i<k;i++) { cout<<c[i]; } } k=0; if(ch==1) { for(i=0;i<n;i++) { for(j=0;j<m;j++) { if(a[i]==b[j]) { c[k]=a[i]; k++; break; } } } cout<<"\nINTERSECTION "; for(i=0;i<k;i++) { cout<<c[i]; } } cout<<"\nWANT TO EXIT?(enter1)"; cin>>choice; if(choice==1) break; }}

OUTPUT:

iv. Write a program to write some names and store them into corresponding files according to the alphabets and tell the location where they are placed.
#include<fstream.h> #include<conio.h> void main() { clrscr(); int A=0,B=0,C=0,D=0,nc[20],mc[20],ac[20],sc[20]; char p; do { char word[20]; cin>>word; ofstream n; n.open("nf.txt",ios::app); ofstream m; m.open("mf.txt",ios::app); ofstream a; a.open("af.txt",ios::app); ofstream s; s.open("sf.txt",ios::app); if(word[0]=='n') { n<<word<<endl; A++; } if(word[0]=='m') { m<<word<<endl; B++;

} if(word[0]=='a') { a<<word<<endl; C++; } if(word[0]=='s') { s<<word<<endl; D++; } n.close(); m.close(); a.close(); s.close(); cout<<"file is created "; cout<<endl<<"locations of n are::"<<A<<endl; cout<<endl<<"locations of m are "<<B<<endl; cout<<endl<<"locations of a are "<<C<<endl; cout<<endl<<"locations of s are "<<D<<endl; cout<<"do u want to continue?? enter y else n\n"; cin>>p; } while(p=='y'); getch(); }

Output:

v.

Write a program to read and write a string into a file.

#include<iostream.h> #include<conio.h> #include<fstream.h> #include<stdio.h> #include<string.h> void main() { clrscr(); char indata[100]; cout<<"\nENTER THE DATA TO BE WRITTEN ON FILE\n"; gets(indata); ofstream q("data.txt"); q<<indata; q.close(); char o; cout<<"\nTHE DATA IN FILE IS::::\n"; ifstream w("data.txt"); while(w) { w.get(o); Cout<<o;} w.close(); getch(); }

Output:

vi. Write a program to create a file for student (name, roll. no , marks) and perform the following operations a) Store name , roll. no , marks of students into a file. b) Print the contents of the file. c) Add one or more student information into the file. d) Print total number of students in the file. e) Modify any student information.

#include<iostream.h> #include<conio.h> #include<fstream.h> #include<iomanip.h> class student { char name[10]; int rn; float marks; public: void getdata() { cout<<"Enter name";cin>>name; cout<<"Enter Roll No.";cin>>rn; cout<<"Enter Marks";cin>>marks; }

void showdata() { cout<<setw(10)<<name<<setw(10)<<rn<<setprecision(2)<<setw(10)<<marks<<endl; } }; void main() { clrscr(); int q; cout<<"Enter the no. of students::"; cin>>q; student std; fstream file; file.open("sun.txt" , ios::out|ios::binary); for( int i=1;i<=q;i++) { cout<<"Enter the information of"<<i<<"student\n"; std.getdata(); file.write( (char*) & std,sizeof(std) ); } file.close(); file.open("sun.txt",ios::ate|ios::in|ios::out|ios::binary); file.seekg(0,ios::beg); while(file.read((char*)&std,sizeof(std))) {

std.showdata(); } file.clear(); cout<<"Add another student to the data\n"; std.getdata(); file.write((char*)&std,sizeof(std)); file.seekg(0); clrscr(); while(file.read((char*)&std,sizeof(std))) { std.showdata(); } int last=file.tellg(); int n=last/sizeof(std); cout<<"\nNo. of students in the file="<<n<<endl; cout<<"Total bytes in file="<<last<<endl; cout<<"Enter the student no. to be modified"; int objno; cin>>objno; int location=(objno-1)*sizeof(std); if(file.eof()) file.clear(); file.seekp(location); cout<<"Enter new values for student"; std.getdata(); file.write((char*)&std,sizeof(std));

file.seekg(0); clrscr(); cout<<"contents of updated file\n"; while(file.read((char*)&std,sizeof(std))) { std.showdata(); } file.close(); getch();}

Output:

S-ar putea să vă placă și