Sie sind auf Seite 1von 38

EASWARI ENGINEERING COLLEGE RAMAPURAM, CHENNAI-89

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

LAB MANUAL

185253

COMPUTER PRACTICE LABORATORY II

Prepared By

Approved by

Ms.S.PONMANI Ms.K.AKILA Ms.V.SUDHA Mr.N.DURAIMURUGAN Mr.N.BHARATHIRAJA

HOD/CSE

185253 COMPUTER PRACTICE LABORATORY II

L T P C 0 1 2 2

LIST OF EXPERIMENTS 1. UNIX COMMANDS Study of Unix OS - Basic Shell Commands - Unix Editor 2. SHELL PROGRAMMING Simple Shell program - Conditional Statements - Testing and Loops 3. C PROGRAMMING ON UNIX Dynamic Storage Allocation-Pointers-Functions-File Handling TOTAL : 45 PERIODS
HARDWARE / SOFTWARE REQUIREMENTS FOR A BATCH OF 30 STUDENTS

15

15

15

Hardware 1 1 UNIX Clone Server 2 33 Nodes (thin client or PCs) 3 Printer 3 Nos. Software 4 OS UNIX Clone (33 user license or License free Linux) 5 Compiler - C

LIST OF EXPERIMENTS I UNIX COMMANDS 1. 2. 3. Study of UNIX OS Basic Shell Commands Unix Editor II SHELL PROGRAMMING 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. Greatest among three numbers Factorial of a given number Sum of Odd numbers upto n Generation of Fibonacci numbers Implement the Arithmetic calculator Converting temperature in Fahrenheit to Degree Centigrade. Check whether given string is a palindrome or not Check whether the given year is leap year or not The largest digit of a number Sum of n different numbers sum of digits of a number Generate prime numbers between 1 and 50 Area and circumference of a circle Check the given number and its reverse are same Sum of odd and even numbers from a set of numbers
3

C Programming on UNIX 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. Program to reallocate the string using dynamic memeory allocation Program to interchange the values stored in 2 variables using function with pointers. Program to create a file and display its content Program to perform file copy operation Program to create two files and perform merge operation on it Program to find the sum of n numbers using function. Program using dynamic memory allocation to develop salary details of 5 employees. Program using dynamic memory allocation to find the sum of elements of a matrix. Program to print addition, subtraction and multiplication values using functions. Program to perform file manipulation like copying file, changing the case of the entire file and to count the number of words, spaces and lines in a file..

STUDY OF UNIX OPERATING SYSTEM UNIX Introduction What is UNIX? UNIX is an operating system which was first developed in the 1960s, and has been under constant development ever since. By operating system, we mean the suite of programs which make the computer work. It is a stable, multi-user, multi-tasking system for servers, desktops and laptops. UNIX systems also have a graphical user interface (GUI) similar to Microsoft Windows which provides an easy to use environment. However, knowledge of UNIX is required for operations which aren't covered by a graphical program, or for when there is no windows interface available, for example, in a telnet session Types of UNIX There are many different versions of UNIX, although they share common similarities. The most popular varieties of UNIX are Sun Solaris, GNU/Linux, and MacOS X. Here in the School, we use Solaris on our servers and workstations, and Fedora Linux on the servers and desktop PCs. The UNIX operating system The UNIX operating system is made up of three parts; the kernel, the shell and the programs. The kernel The kernel of UNIX is the hub of the operating system: it allocates time and memory to programs and handles the filestore and communications in response to system calls. As an illustration of the way that the shell and the kernel work together, suppose a user types rm myfile (which has the effect of removing the file myfile).
5

The shell searches the filestore for the file containing the program rm, and then requests the kernel, through system calls, to execute the program rm on myfile. When the process rm myfile has finished running, the shell then returns the UNIX prompt % to the user, indicating that it is waiting for further commands. The shell The shell acts as an interface between the user and the kernel. When a user logs in, the login program checks the username and password, and then starts another program called the shell. The shell is a command line interpreter (CLI). It interprets the commands the user types in and arranges for them to be carried out. The commands are themselves programs: when they terminate, the shell gives the user another prompt (% on our systems). The adept user can customise his/her own shell, and users can use different shells on the same machine. Staff and students in the school have the tcsh shell by default. The tcsh shell has certain features to help the user inputting commands. Filename Completion - By typing part of the name of a command, filename or directory and pressing the [Tab] key, the tch shell will complete the rest of the name automatically. If the shell finds more than one name beginning with those letters you have typed, it will beep, prompting you to type a few more letters before pressing the tab key again. History - The shell keeps a list of the commands you have typed in. If you need to repeat a command, use the cursor keys to scroll up and down the list or type history for a list of previous commands. Files and processes Everything in UNIX is either a file or a process. A process is an executing program identified by a unique PID (process identifier). A file is a collection of data. They are created by users using text editors, running compilers etc.

Examples of files:

a document (report, essay etc.) the text of a program written in some high-level programming language instructions comprehensible directly to the machine and incomprehensible to a casual user, for example, a collection of binary digits (an executable or binary file); a directory, containing information about its contents, which may be a mixture of other directories (subdirectories) and ordinary files.

The Directory Structure All the files are grouped together in the directory structure. The filesystem is arranged in a hierarchical structure, like an inverted tree. The top of the hierarchy is traditionally called root (written as a slash / )

In the diagram above, we see that the home directory of the dergraduate student "ee51vn" contains two sub-directories (docs and pics) and a file called report.doc. The full path to the file report.doc is "/home/its/ug1/ee51vn/report.doc"
7

Starting an UNIX terminal To open an UNIX terminal window, click on the "Terminal" icon from the drop-down menus

UNIX - Basic Commands The basic form of any UNIX command is:command_name options argument(s)

Unix is case-sensitive. Unix distinguishes between upper and lower case letters in the names of files and programs. Thus, while ls is a valid Unix command, LS is not. Login names and passwords are also case-sensitive. A filename in Unix can consist of any combination of characters on the keyboard except for the space bar and all of the following : * ? ! \ \ > ;, ^ ( ) $ ~. These characters cannot be used in filenames because they have special meaning to the shell. For instance, the first two characters are used as wildcards.
8

Directory Related Commands: S.No 1. 2. 3. 4. Command pwd mkdir rmdir cd Description Print working directory Create an empty directory in the disk Remove a directory from the disk. (Directory must be empty) Change current working directory

pwd 1.Syntax:$ pwd Output: /root/user1 where user1 refers to the present working directory mkdir 2.Syntax: $ mkdir dirname Example: $ mkdir asha This creates a directory with name asha rmdir 3.Syntax:$ rmdir dirname Example:$ rmdir asha This deletes the directory named asha cd 4.Syntax:$ cd dirname Example:$ cd uma Changes from current directory to directory uma File Related Commands S.No 1. 2. 3. 4. 5. 6. 7. Command cat cp rm mv ls ln wc Description To create a new file on the system and to display the contents of a file. To copy the contents of a file. To remove a file To rename a file To list files and directories To make a link or to create aliases To count the total number of lines,words and characters of a given file.
9

8. 9. 10. 11. 12. 13. 14. 15.

find file chmod nl more less pg spell

Locates the files both in the directories and subdirectories by performing recursive searches. To get the type of the file. To set the access permission for Owner,Group and Others. Adding line numbers to a file. To display the contents of a file one screen at a time To display the contents of a file one screen at a time To display the contents of a file one page at a time To fine spelling errors in a file and to display them on the standard output in alphabetical order

Cat 1 .Syntax:$ cat options filename To create a file Syntax: $ cat > filename Example: $ cat > file1 Creates a file named file1 To display the contents Syntax: $ cat filename Example: $ cat file1 Display the contents of file1

To append contents to a file Syntax: $ cat >> filename Example: $ cat >> file1 Append the contents to file1 Option : -n Number the lines of the file including blank lines

10

Cp 2.Syntax:$ cp sourcefile destinationfile Example: $ cp file1 file2 Copies the contents of file1 to file2 rm 3. Syntax:$ rm filename Example: $ rm file1 Deletes file1 mv 4. Syntax:$ mv sourcefile destinationfile Example: $ mv file2 file3 Contents of file2 are moved to file3. (Nothing but renaming file2 as file3.file2 no longer exists) ls 5.Syntax:$ ls -options ls -l list the files in long format ls -t list the files in the order of last modification time ls a list all files including hidden files ls c list all files column-wise ls d list the directory rather than its contents ls m list all files separated by columns ln 6.Syntax:$ ln options filename1 filename2 Example:$ ln file1 file2 file1 will have two names as file1 & file2 but with a single copy of contents wc 7.Syntax:$ wc option(s) file(s) wc c counts the number of characters in the file wc w counts the number of words in the file wc l counts the number of lines in the file find 8.Syntax:$find search_path search_expression
11

Example:$find /usr1 ab*.c The above command will search for the files starting with letters ab and with extension c in the path /usr1 file 9.Syntax:$file filename Example:$file file1 Will determine the type of file1 chmod 10.Syntax:$chmod usertype operation access_permission file(s) where usertype owner(u),group(g),others(o) or all(a) operation add(+) or remove(-) access_permissionread(r),write(w) and execute(x) file(s) - one or more files Example:$chmod g -r o r uma.dat This denies the read access of group and others for filename priya.dat Octal Notation: Read Permission 4 Write Permission 2 Execute Permission 1 (e.g) chmod 761 file1 Assigns all permissions to the owner, read and write permissions to the group, and only executable permission to the others for file1 nl 11.Syntax :$ nl options filename Example:$ nl file1 This will add line numbers to the left of each line in file1 Option: -p Doesnt restart numbering when encounters page break more 12.Syntax:$ more options file(s) Options: -c Clears the screen and displays the file contents by beginning at the top of the screen -d Displays the prompt
12

-h

Displays help information for all more commands

less 13.Syntax:$ less options file(s) Options: -c Clears the screen and displays the file contents by beginning at the top of the screen -N Displays the contents of the file with its line numbers -h Displays help information for all more commands pg 14.Syntax:$ pg options file(s) Options: -c Clears the screen and displays the file contents by beginning at the top of the screen +n Displays the contents of the file starting from line number n -n Issues a pg command without waiting for you to press the Enter key spell 15.Syntax:$spell options(s) file(s) Option: -b Uses British dictionary for checking Example:$spell b file1 This will check for spelling mistakes in file1 using British dictionary General Purpose Commands S.No 1. 2. 3 4 5 6. 7. Command date bc echo cal man clear expr Description To display both system date and time. (Binary calculator) To perform simple mathematical calculations Displays each of the arguments on the standard output To display the calendar of any specific month of the year or a complete year. To obtain online help on any command. To clear the screen. To evaluate an expression
13

8.

factor

Factorise a number and print its prime factors

date 1.Syntax:$date option(s) Options: +%a Displays the abbreviated weekday(sun to sat) +%A Displays the full weekday name(Sunday to Saturday) +%B Displays the full month name +%c Displays the current date and time +%d Displays the day of month +%H Dislays the hour +%M Displays the minute +%S Dislays the seconds +%Y Displays the four digit year Example:$date +TIME: %H: %M: %S Output: TIME: 14:38:32 bc 2.Syntax:$bc Example:$bc sqrt(9) 3.00 1+2 3 Ctrl+d(to quit from bc) echo 3.Syntax:$echo string Example:$echo Introduction to unix Output: Introduction to unix cal 4.Syntax:$cal [month] [year] Example:$cal 10 2003 This displays the calendar for the month of October in year 2003 man 5.Syntax:$man command Example:$man ls
14

This displays information about ls command clear 6.Syntax:$ clear expr 7.Syntax:$expr `expression` Example:$expr ` 100 + 50 ` 150 Ctrl+d(to quit) factor 8.Syntax:$factor Example:$factor 28 2 2 7 Ctrl+d(to quit) About Yourself and Other People S.No 1. 2. 3. 4. 5. 6. Command who am i du du sk w who talk write Description Returns the current username. This command can be used to find out if someone is already logged on and had forgotten to log out. Shows the disk usage of the files and the directories in filename will give a total of all files and directories on the disk Tells you whos logged in, and what theyre doing. Tells you whos logged on, and which computer they are logged on to.. Lets you have a typed conversation with another user Lets you exchange one line messages with another user

who am i 1.Syntax:$who am i du
15

2.Syntax:$du option filename Example:$du k file1 w 3.Syntax:$ w who 4.Syntax:$ who talk 5.Syntax:$ talk username write 6.Syntax:$ write username Input/Output Redirection Apart from the standard input available in Unix, input can be taken from other sources and can be passed to any destination other than the standard outputs. This process is called redirection. There are two types of redirection: 1.Input Redirection 2.Output redirection Output Redirection When output from a process is redirected to any destination other than the standard output (i.e) terminal, it is called output redirection Syntax: $ command > filename Here the output is redirected to the file specified. Example: $date > today This command sends the output of date command to the file today. We can also redirect the output of a command to a file in an append mode. Syntax:
16

$command >> filename Example: $who >> students The output of the who command will be appended to the students file. Input Redirection When the input is redirected from a source file rather than a standard input it is called as input redirection. Syntax: $command < filename Here filename is the input source. Example: $cat < student The contents of the student file is the input to the cat command. Combining standard input and output redirection Both input and output redirection can be combined in a command. The < and > operators can be combined to use both forms of redirection in a single command line. Example: $wc < student > student1 First the contents of the student file is given as input to wc command whose output is redirected to student1. Pipes and Filters In Unix, commands are used to perform single tasks only. If at all we want to perform multiple tasks in one command, it is not possible. Redirection provides solution to this problem. But, it creates lot of temporary files, which are redundant and occupy more disk space. Pipes and filters provides the solution to this problem. Pipes Pipes is a mechanism which takes the output of a command as the input for the next command.
17

Example: $ who > student $ wc l student 4 The above example illustratres there are four users currently logged in. This command uses the files and direction operators to get the number of users. The same result can be obtained with the help of pipes as shown below $ who | wc l 4 The output of the who command is the input for the wc l command

Exercise 1. Create the following directory structure in UNIX CSE PG UG

2. Create files under CSE with extensions like *.txt, *.c etc. 3. Display all files with extension txt 4. Rename all files with extension txt to dat 5. Copy the files with extension C to UG directory 6. Delete all the files with extension C from CSE directory rm *.c 7. Display all files with 2 character filename and extension .txt

18

8. To create a file with a list of subject name and to display the first and last three subjects stored in that file 9. To list the contents of a file from fourth subject from the end of file and also to list the contents of a file from seventh subject from the beginning of the file 10.Create a file named INDIA, which contains the following data India is my country All Indians are my Brothers and Sister I love my country a) Use the filter command to search for the pattern my b) Display all the lines that do not contain the above pattern c) Count the total number of lines containing the pattern my d)Display all the lines which contains the pattern country 11.Create a file containing 10 lines of information. Count the number of lines, number of words and number of characters. 12.Redirect the contents of ls p to a file called LISTING. 13.Create a file called EMP as given below: E002: malar: mktg: 5000 E001: balan: acct: 7000 a) Sort the file on the employees department. b) List the employees who earn between 4000 and 6000. 14. Add line numbers to the content of a file INDIA 15. Display who is on the system. 16.Display the entire text of the file EMP in uppercase. 17. write sa command to Combine two strings. 18. Write and execute the following the following commands (i) Create two files with the name of name.txt, which contain only names, and reg.txt with the content of register number respectively.
19

(ii) Combine the two files in the form of register number followed by name (iii) Sort the two files in ascending order 19.. Write and execute the following UNIX commands (i) Execute more than one command at a time (using semi-colon ;) (ii) Display the users full details. (iii) Display the user-id / Group-id. (iv) Execute more than one command at a time (using logical-AND &&). 20. Write and execute the following UNIX commands (i) Demonstrate pipe command (ii) Demonstrate tee command 21. Write and execute the following UNIX commands (i) Use finger command (ii) Use grep command (iii) Use diff command (iv) Use uniq command (v) Use cmp command 22. Write and execute the following UNIX commands (i) Count the specific number of lines from a file start from the beginning of the file (ii) To destroy a specific file from a user directory (iii) Send a greeting message to other user 23. Write and execute the following UNIX commands (i) To view all the files and directories page by page (ii) To view only the directories page by page (iii) Display the complete path of the working directory 24. Write and execute the following UNIX commands (i) To check the working directory (ii) Change the password (iii) To display todays date (iv) To display the calendar of this month (v) To display a message University Exam using a special character

20

VI EDITOR It is used to create and edit a text file or program. The vi editor has the following three modes. 1. Command mode 2. Colon mode 3. Input mode COMMAND MODE: In this mode the user can move anywhere in the screen. VI EDITOR COMMANDS IN COMMAND MODE: Press Esc key and then use the following keys i used to enter text before the cursor. a used to enter text at the end of the line. x used to delete a character at the cursor position. dd used to delete a line at the cursor position. dw used to delete a word at the cursor position. e used to move the cursor to the beginning of the word. o used to open a new line position the cursor at the start of the line and enter text. ^ used to move the cursor to the beginning of the line. $ used to move the cursor to the end of the current line. ctrl+d used to move down the file half a screen. ctrl+u used to move up the file half a screen. COLON MODE In this mode complicated operations that are normally not possible using simple key strokes can be performed. VI EDITOR COMMANDS IN COLON MODE Press Esc then use following keys. :q used to quit vi editor. :q! used to quit vi editor without saving file. :w used to save the file and to remain in the vi editor. :wq used to save the file and to quit the vi editor. :o used to move cursor to the beginning of the file. :$ used to move cursor to the end of the file. :n used to move cursor to the start of particular number.
21

:setnu used to set the line number. INPUT MODE: In this mode the cursor is allowed to enter text after pressing the Esc key followed by any other commands. Shell Programming Shell or the command interpreter is a program that interprets ur request to run the UNIX commands. Set of commands can be grouped together under a single filename and executed and this is done using shell scripts.

Types of shell: Bourne shell C shell Korne Shell sh csh ksh

Creation and execution of shell scripts using command line editor: 1. creation $ cat > greet echo please enter your name: read name
22

echo hi! Welcome to this session $name Ctrl + D 2. Execution $ sh greet please enter your name: jaya hi! Welcome to this session jaya VALID SHELL VARIABLES: n area a1 account a_count ASSIGNING VALUES TO VARIABLE: Variable=value DISPLAYING VALUES OF VARIABLES: 1. $ echo value of n is $n Operators Arithmetic Operators provided by the shell are +,- * and / Note: precede * symbol by backslash(\) to make a difference from wildcard character (ex . \* 5) Logical operators -a and -o or ! not Relational operators -eq : check fro equality of integers -ne : check for inequality -gt : check if one integer is greater than the other -lt : check if one integer is lesser than the other -ge : check if one integer is greater than or equal to the other -le : check if one integer is lesser than or equal to the other. -f : check if a file is an ordinary file -d : check if a file is a directory -r : check if a file is readable
23

-w -x

: check if a file is write able : check if a file is executable

String comparison operators = equal to != not equal to Logical operators -a and -o or -! Not Conditional execution operations && used to execute a command on successful execution of another command. || used to execute another command on failure of another command. Read command Used to read the value of the shell variable from a user. Comment statement # this is a text program. Programming language construct 1.a)if..thenelsefi 2.fordodone 3.while..do..done 4.untildo..done 5.case esac 1)if construct useful for executing a set of commands based on the condition being true and alternate set of commands to be executed if the condition is false. Ex. if (grep India countri.dat) then echo pattern found else echo pattern not found fi
24

b) if..then..elif..else ..fi

2)for construct used to perform same set of operations on a list of values. for variable in value1 value2 value3 do Commands done Ex. for k in 1 2 3 4 5 do echo the number is $k echo the square of the number is `expr $k \* $k` done 3)while construct Repeatedly executing group of commands as long as the condition is true. while condition do Commandlist done Ex.to print 3 numbers a=1 while [$a -le 3] do echo $a $a=`expr $a+1` done o/p. 1 2 3 4.until construct Repeatedly executing group of commands until a condition is true. until condition do Commandlist done
25

Ex.to print 3 numbers a=1 until [$a -le 3] do echo $a $a=`expr $a+1` done o/p. 1 2 3 5. case construct case value in choice1) commands;; choice2)commands;; . esac $echo enter a value read myval case $myval in 0) echo zero;; 1) echo one;; 2) echo two;; 3) echo three;; *) echo invalid argument;; esac test command: Used to test for equality and it returns a true or false as a result. Syntax: test condition Exercise: 1. Greatest among three numbers Algorithm: Step 1. Read 3 numbers n1,n2 and n3 Step 2. Check if n1 is greater than n2 check n1 is greater than n3 also announce n1 as greatest announce n3 as greatest else, check whether n2 is greater than n3 if yes, announce n2 as greatest
26

Ex.

else announce n3 as greatest 2. Factorial of a given number Algorithm: Step 1. Read n Step 2. Initialize fact to 1 and i to n Step 3. Repeat the following until i>0 Assign fact * i to fact Decrement i by 1 3. Sum of Odd numbers upto n Algorithm: Step 1. Read n Step 2. Initialize x=1 and sum=0 Step 3. Repeat the following until x < n Assign sum + x to sum Increment x by 2 4.Generation of Fibonacci numbers Algorithm: Step 1. Read n Step 2. Initialize p=-1, q=1 and I=1 Step 3. Repeat the following until I < n Assign p + q to r Assign q to p Assign r to q Increment I by 1 5.Implement the Arithmetic calculator Algorithm: Step 1. Read a, b and option Step 2. According to the option perform the operation 6. Write a shell program to convert temperature in Fahrenheit to Degree Centigrade. Algorithm: Step 1. Read f Step 2. Assign (f-32) * 5/9 to c

27

7.Check whether given string is a palindrome or not. Algorithm: Step 1. Read a String Step 2. Find the length of the string Step 3. Start reading from the last character to the first character and store it as a new string in temp Step 4. Compare both the strings, if it is same the given string is palindrome 8. Check whether the given year is leap year or not Algorithm: Step 1. Read year Step 2. Divide the year by 4, if the remainder is zero the given year is leap. 9. Write a Shell program to find the largest digit of a number. Algorithm: Step 1: Get a number from the user Step 2: Obtain individual digit for the above number using modulo operator Step 3: Initialize variable max with first digit Step 4; Compare the value of max with the other digits, if the value of max is lesser update the value of max Step 5: Display the value of max

10.Write a Shell program to find the sum of n different numbers Algorithm: Step 1: Get array of n numbers Step 2; Using for loop , add the numbers Step 3: Display the sum. 11.Write a Shell program to find the sum of digits of a number Algorithm: Step 1: Get a number from the user Step 2: Obtain individual digit for the above number using modulo operator Step 3: perform sum Step 4: Display the sum
28

12.Write a Shell program to generate prime numbers between 1 and 50 Algorithm: Step 1: Get a number and initialize i as 2 Step 2: if i<=number/2 goto step 3 Step 3: if number mod i == 0 print not prime Step 4: increment I by 1 and goto step 2 Step 5: if i==number print the number is prime Step 6: Repeat above steps for numbers between 2 and 50. 13.Write a Shell program to find the area and circumference of a circle Algorithm: Step 1: Get the radius of circle Step 2: Calculate area = 3.14*r*r Step 3: Calculate circumference = 2*3.14*r Step 4: Display the results 14.Write a Shell program to check the given number and its reverse are same Algorithm: Step 1: Get a number from the user Step 2: Set a loop upto the number is not equal to zero Step 3: reminder=number%10 Step 4:rnum=rnum*10+reminder Step 5: number=number/10 Step 6: if number==rnum print both are same 15. Write a Shell program to find the sum of odd and even numbers from a set of numbers Algorithm: Step 1: Get n numbers Step 2: initialize evensum and oddseum as 1 Step 3: create a loop for n times if (a[i]%2==0) evensum =evensum+a[i] else oddsum=oddsum+a[i] Step 3: Display the result.
29

C Programs on UNIX 1. To Demonstrate a. malloc() malloc: Allocates memory Declaration: void *malloc(size_t size); malloc allocates a block of size bytes from the memory heap. It allows a program to allocate memory explicitly as it's needed, and in the exact amounts needed. The heap is used for dynamic allocation of variable-sized blocks of memory. Many data structures, such as trees and lists, naturally employ heap memory allocation. All the space between the end of the data segment and the top of the program stack is available for use in the small data models, except for a small margin immediately before the top of the stack. This margin is intended to allow the application some room to make the stack larger, in addition to a small amount needed by DOS. In the large data models, all the space beyond the program stack to the end of available memory is available for the heap. Return Value: On success, malloc returns a pointer to the newly allocated block of memory. On error (if not enough space exists for the new block), malloc returns null. The contents of the block are left unchanged. If the argument size == 0, malloc returns null. calloc : Allocates main memory Declaration: void *calloc(size_t nitems, size_t size); calloc provides access to the C memory heap, which is available for dynamic allocation of variable-sized blocks of memory.
30

b) calloc()

c)realloc

Many data structures, such as trees and lists, naturally employ heap memory allocation. calloc allocates a block (nitems * size) bytes and clears it to 0. To allocate a block larger than 64K, use farcalloc. Return Value: On success, returns a pointer to the newly allocated block. On failure (not enough space exists for the new block, or nitems or size is 0), returns null. Example: str=(char *)calloc(10,sizeof(char)); realloc: realloc reallocates main memory Declaration: void *realloc(void *block, size_t size); realloc adjusts the size of the allocated block to size, copying the contents to a new location if necessary. Argument block What it is/Does Points to a memory block previously obtained by calling malloc, calloc, or realloc. If block is a null pointer, realloc works just like malloc. Points to a memory block previously obtained by calling farmalloc, farcalloc, or farrealloc. New size for allocated block New size for allocated far block (in bytes)

oldblock

size nbytes .

Return Value: On success, both functions return the address of the reallocated block, which might be different than the address of the original block. On failure (if the block can't be reallocated, or if size == 0 for realloc), the functions return null. Example #include <stdio.h>
31

#include<string.h>#include<alloc.h> #include<process.h> void main() { char *str; str=(char *)malloc(10); strcpy(str,Hello World); printf(Address of String is %d, str); str=(char *)realloc(str,20); printf(New Address of String is %d, str); free(str); } FILES A File is a collection of related information, that is permanently stored on the disk and allows us to access and alter the information whenever necessary. HIGH LEVEL FILE Operations (Opening and Closing of File) We can perform the following basic operations on Files. Naming a file Opening a file Reading data from a file Writing data to a file Closing a file There are large number if standard library functions available for performing disk files. i. ii. High level file I/O functions Low level file I/O functions

High level file I/O functions do their own buffer management, whereas in low level file I/O functions buffer management has to be done by the programmer. Some of the high level file I/O functions. Function fopen() fprintf() fscanf() fseek() Purpose Used to create or open a file. Used to write data to the file Used to read data from the file. Used to position the desired point.
32

ftell () fclose() feof() fputc() fgetc() rewind() remove() ffush()

Used to specify the current position. Used to close an opened file. Used to find, if end of file is encountered. Used to write a character to a file. Used to read a character from file. Used to move control to the beginning of the file. Used ti erase a file Used to flush a file.

OPENING AND CLOSING OF FILE Opening a file A data file must be opened before it can be created or processed, this associates the file name with buffer area. Opening a file means,creating a new file with specified file name and with accessing mode Syntax:
FILE *fp; fp=fopen(filename,mode);

The data structure of the file s defined as FILE in the standard I/O library function definitions. Therefore, all files should be declared as type FILE before they are used. The first statement declares the variable, fp as a pointer to the data type FILE. The Second statement opens the file named filename and assigns identifier to the FILE type pointer fp. This pointer which contains all the information about the file and it is used as a communication link between the system and the program. The mode in the second statement specifies the purpose of accessing the file like read, write etc. File accessing modes Mode r w a r+ w+ a+ Purpose Used to open the file for reading purpose. Used to open the file for writing purpose. Used to appending data into the file. Used to open an existing file for reading and writing. Used to open a new file for both reading and writing. Used to open an existing file for both reading and writing.
33

When the file is opened in the write mode, if the file does not exist it is created, and the contents are deleted if that file already exists. When the file is opened in the read mode if the file exists the file is opened with the current contents safe, otherwise and error occurs. Example : fp=fopen(Input,w); It opens the file input in the write mode. If input file already exists its contents are deleted. If it does not exist, the input file is created. We can open and use a number of files at the time. This number however depends on the system we use. Closing a file A file must be closed after all the operation of the file have been completed. Syntax :
fclose(file-pointer);

By doing this all the information associated with the file is flushed out from the buffers and all links to the file are broken. It also prevents any accidental measure of the file. Example : fclose(fp); In the above example the statement fclose(fp) is used to close a file, after all operations on them are completed and used to change the mode of operation. File pointer can be used for another file. All files are closed automatically whenever a program terminates. OPERATIONS ON SEQUENTIAL AND RANDOW ACCESS FILES Types of files We are going to discuss three types of files mainly, and these types of files are formed depending on the organization of data in the file.
i. ii. Sequential file Random Access file.

34

sequential file As the name implies that the records are stored and retrieved sequentially i.e.,one after another. Sequential file is a data structure which consists of a sequence of records of the same type and size. The records in the file can be read only sequentially. i.e., One after another starting from the beginning of the file The primary advantage of a sequential file compared to an any other file is that it can grow or shrink dynamically. The sequential access is the disadvantage. Usually the records in the file are arranged in ascending or descending order of the key fields. To understand the sequential file, lets start with an example. Consider the example of a tape or cassette where the songs are stored sequentially. Storing data sequentially is the simplest form of file, but a tedious one. Reading data to a file or writing data from it takes a lot of time as the data is not stored. The data is stored on FCFS (First Come First Server) basis. Taking example where we want to retrieve as record which is unfortunately stored at the last position in the Random Access Files In case of sequential file , we are writing records in the sequential file as they come. But in direct access files, we write the record to a particular position. Since we are deciding the position of the particular record, there is some relation between the key using which we are deciding the position of the record. Hence using the relation between the key and record number, we can determine if a given record is present in the file or not. To access particular part of file we have the following functions ftell( ) fseek( ) rewind( ) i)ftell( ) this function is used to specify the current position of a file. It makes the file pointer and returns a number of type long, that corresponds to the current position. n=ftell(p); where n is the relative offset of the current position in bytes ii) fseek( )- It is usd to move the file position to a desired location within a file. fseek(fileptr,offset,position); fileptr-is a pointer in the file concerned offset-is a number or variable of type long position is an integer, its specifies the number to be moved from the location specified by position.
35

iii)rewind( ) It is used to takes a file pointer to the starting position of the file and resets the position to the start of the file. rewind(fp); n=ftell(fp); where 0 is assigned to n, because the file position has been set to the start of the file by rewind. Exercise 1. Write a C program using pointers to allocate a memory for the string University and reallocate the memory for the string to University Examinations. Algorithm: Step 1: Declare a string variable Step 2: Allocate memory for the string university using malloc function Step 3: Reallocate memory for the variable with the string university examination using realloc function 2.Write a program to interchange the values stored in 2 variables using function with pointers. Algorithm: Step 1: Declare the function to interchange the variables Step 2: Declare and initialize the two integer variables Step 3: Print the values of two variables before interchange Step 4: Call the function to interchange the values of two variables Step 5: Print the interchanged values 3.Write a C program to create a file, which contains register number, name, age etc. and display the content of the file. Algorithm: Step 1: Create a file with the above data . Step 2: Open the file and display the content. Step 3: Close the file. 4.Write a program to perform file copy operation. Algorithm: Step 1: Open a the above the file in read mode Step 2: Open destination file in write mode Step 3: Read the content of source file and write it in destination file. Step 4: Close both the files.
36

5.Write a program to create two files and perform merge operation on it Algorithm: Step 1: open a file1 in read mode and file2 in write mode Step 2: using fseek( ) move file2 ptr to end of the file Step 3: Read the content of file1 and write it in file2 Step 4: close both the files. 6.Write a C program to find the sum of n numbers using function. Algorithm: Step 1: Create a function sum( ) Step 2: Get n numbers from the user Step 3: Perform sum on it. Step 4: Display the sum. 7.Write a C program using dynamic memory allocation to develop salary details of 5 employees. Algorithm: Step 1: Declare the structure for emp Step 2: Allocate the memory for the structure using malloc( ) Step 3: Get the salary details for 5 employees Step 4: Display it. 8.Write a C program using dynamic memory allocation to find the sum of elements of a matrix. Algorithm: Step 1: Declare 3 arrays a[10][10], b[10][10], add[10][10], Step 2: Get the number of rows and columns as m and n respectively Step 3: Scan the values of the matrices according to the values of m and n. Step 5: Add the two matrices directly and store the values in add[10][10] Step 6: Using for loop print the values of add[10][10] Step 7: End the loop

37

9.Write a program to print addition, subtraction and multiplication values using functions. Algorithm: Step 1: Create separate function for each operation. Step 2: Within each function definition, get two values from the user, perform the respective operation and print values. Step 3: Call the user definied function from the main function. 10.Write a program to perform following file manipulation: Read a file Copy a file Change the case of the entire file Count the number of words, spaces and lines in a file. Algorithm: Step 1: open a file a.txt using fp1 in read mode Step 2: Read the content of the file and display it Step 3: copy operation : Open another file b.txt using fp2 , Set fp1 to starting of the file using fseek( ) Read the content of a.txt using fp1 and put it in the b.txt Display the content of b.txt Close the files Step 4: To change the case : Open another file b.txt in read mode Read the content of file using ch=getc( ) If ch is between 91 to 65 add 32 to it else if ch is between 97 to 122 subtract 32 from it now print the ch close the file Step 5:To count the no. of words, spaces and lines in a file Open another file b.txt using fp2 in read mode Read the content of file using ch=fgetc( ) If ch== then words++ else if ch== \n then lines++ else character++ Display no. of words is lines+space No. of lines is lines No. of letters is words+space+lines No. of spaces is spaces
38

Das könnte Ihnen auch gefallen