Unix Lab - II Sem Manual
Unix Lab - II Sem Manual
Unix Lab - II Sem Manual
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
15
15
15
TOTAL : 45 PERIODS
Hardware 1 UNIX Clone Server 33 Nodes (thin client or PCs) Printer 3 Nos. Software OS UNIX Clone (33 user license or License free Linux) Compiler - C
2. Command: who This command gives us the details of who all have logged into the Unix system currently. (eg) $ who abc tty0 feb 26 11:17 xyz tty4 feb 26 11:30 gef tty9 feb 26 11:48
3.Command: who am i This Command identifies the user and lists the user name, terminal name, the date and the time of login. (eg)$ who am i abc tty0 feb 26 11:17 4.Command: date This command is used to display current date. (eg)$date Mon feb 26 13:30:45 1st 2009 The date command can also used with following format specifications. Format +%m +%h +%d +%y +%H Purpose To display only month To display month name To display day of month To display last 2 digits of the year To display Hours 2
+%M +%S
5. Command: cal This command is used to print the calendar details $cal 2009 Print the calendar for the entire year. $cal 4 2009 Print the calendar for the month of april 2003 6: Command: clear This command is used to clear the screen. (eg) $ clear $ tput clear 7.Command: wc This command is used to count the number of lines, words or characters in a file. (eg) $ wc count The following options are used with wc command. wc-l - used to display only number lines. wc-w - used to display only number of words. wc-c - used to display only number of characters. 8.Command: bc:The unix calculator is programmable and has complex functions. It doesnt displays command prompt and it simply waits for you. Type your calculations. (eg) $ bc 5+5 10 bc continuous , this process until you enter ctrl+d to terminate.
WORKING WITH FILES 1.Command: Mkdir This command helps us to make a directory. (eg) $ mkdir temp 2.Command: cd This command is used to change from the working directory to any other directory specified. (eg) $ cd student 3.Command: cd .. This command is used to come out of the current working directory. (eg) $ cd .. 4.Command: pwd This command has no options. It tells us the full path name for the current directory we are working in. 3
(eg) $ pwd 5.Command: rmdir This command is used to remove a directory specified in the command line. (eg) $ rmdir temp 6.Command: cat (a) cat filename: This command helps us to list the contents of a file we specify. (eg) $ cat xyz (b) cat > filename: This command helps us to create a new file we specify. (eg) $ cat > xyz (c) cat >> filename: This command helps us to append a contents to the existing file and if not existing, create a new file we specify. (eg) $ cat >> xyz 7.Command: rm This command is used to remove one or more files from a directory. (eg) $ rm temp/mat 8.Command: cp
This command is used to copy one or more files from a source directory to a target directory
(eg) $ cp temp/mat temp1/mat 9.Command: mv This command is used to move one or more files from a directory. (eg) $ mv temp/mat temp1/mat 10.Command: ls This command is used to find the location. (eg) $ ls
Command Action
ls-l ls-t ls-a ls-d ls-p ls-u Lists all files in the long format Lists in order of last modification time Lists all entries, including hidden files Lists directory file instead of its contents Puts a slash after each directory Lists in order of last access time
INPUT-OUTPUT REDIRECTION PIPES AND FILTERS 1. Input Redirection: The Symbol < is the redirecting input operator. It reads input from the specified file. (eg) $ cat < sample 2. Output Redirection: The Symbol > is the redirecting input operator. It reads input from the specified file. (eg) $ cat > sample 3. Pipes: The pipe is a tool in which the output of one command can be channeled into the input of another command. (eg) $ who | wc FILTERS 4. The Head Filter: It displays the lines from the beginning of a file. (eg) $ head 4 sample It displays top 4 lines of the file sample. 5. The Tail Filter: It displays the lines from the end of a file. (eg) $ tail 4 sample It displays 4 lines from the end of the file sample. 6. The pg filter: It shows the file page by page (eg) $ ls | pg 7. The grep filter: It is used to search and print specified patterns from a file. $ grep [option] pattern file(s) (eg) $ grep asia sample 8. Options available in grep command Command Purpose -v -c Displays only those lines which do not match the pattern specified Displays only the count of those lines which match the pattern speficied Displays those lines which match the pattern specified along with the line number at the beginning of the file. Displays those lines which match the pattern specified ignoring the case distinction. 5
-n
-i
9. The Sort filter: The sort command is used to sort the contents of the file. $sort filename (eg) $ sort sample
10. Options available in sort command Command -r -n -nr -u Purpose Sorts and displays the file contents in reverse alphabetical order Sorts numerically Sorts numbers in reverse order Sorts and removes duplicate records
11. The uniq filter: The uniq filter compares adjacent lines in the sorted input file, and when used with a different option displays single occurrences and multiple occurrences. (eg) $ sort sample | uniq 12. The cut filter: One particular field from any file of from output of any command can be extracted and displayed using the cut command (eg) $ cut d : sample 13. The Paste command: This command merges the contents of two files into a single file. (eg) $ paste sample1 sample2 sample3 PROBLEMS 1. Create a file called student which contains the sample data as follows: S99001 Sneha Kumar 54 S99005 Praveen Kalsi 89
a) Display the contents of a file sorted according to their marks in descending order. Soln: sort +3 rn student Output: S99005 Praveen Kalsi 89 S99001 Sneha Kumar 54
b) Display the names of a student in alphabetical order ignoring the cases. Soln: sort +1 student | cut d f2,3 Output: Praveen Kalsi Sneha Kumar c) Display the list of student who have scored marks between 50 and 80 Soln: grep [5-7][0-9] student Output: S99001 Sneha Kumar 54 d) Display the names of a student and their registration numbers. Soln: cut d f1,2,3 student Output: S99001 Sneha Kumar S99005 Praveen Kalsi e) Sort the file according to the third field and dump it to file called temp. Soln: sort +3 student > temp
Create a file called places which contains the sample data as follows: Bombay India 45677 asia Karachi Pakistan 54876 Asia Nairobi Kenya 32196 Africa
a) List the details for the countries usa, kenya and india Soln: egrep usa | kenya | india places Output: Bombay India 45677 asia Nairobi Kenya 32196 Africa b) List the details for the continent asia ignoring the case. Soln: grep i asia places Output: Bombay India 45677 asia Karachi Pakistan 54876 Asia c) Display the list of those countries whose population is between 40000 and 60000 Soln: grep [4-5][0-9][0-9][0-9][0-9] places Output: Bombay India 45677 asia Karachi Pakistan 54876 Asia 7
Extract the lines which end with ia. Soln: grep ia$ places Output: Bombay India 45677 asia Karachi Pakistan 54876 Asia 1. Create a file called employee which contains the sample data as follows: E0001 : Radha : Personnel : 5000 E0004 : Roja : Finance : 7000
a) Sort the file on the employee department and display the name of the employee and department Soln: sort t : +2 employee | cut d: f2,3 Output: Roja : Finance Radha : Personnel b) List the employees whose basic pay between 4000 and 6000 Soln: grep [4-5][0-9[0-9][0-9] employee Output: E0001 : Radha : Personnel : 5000 c) Sort the file on the employee name in the reverse order. Extract the codes and their names. Soln: sort rt : +1 employee | cut d: f1,2 Output: E0001 : Radha E0004 : Roja d) List the duplicated record of a file and dump it to file called duplicate. Soln: sort t: employee | uniq -d Output: Nil e) Sort the file on the employee codes and extract the basic and names of the non-duplicated lines. Soln: sort t: employee | uniq u | cut d: f2,4
3. PATH variable contains a list of filenames that are to be searched for UNIX commands execution. 4. TERM variable determines the terminal type. 5. LOGNAME variable has our login name. 6. PS2 variable contains the subshell prompt. Positional Parameters The shell scripts can accept arguments from the command line. The arguments are named as $1,$2,$3 etc..and are referred within the script using these names. Since they represent their position they are called positional parameters. Note: The maximum number of positional parameters can be $9. Shift command This command discards the first argument and renumbers the next. 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 -0 or ! not Relational Operators- used for comparing integers within the shell scripts -eq :check for 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 -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 -w :check if a file is writeable -x :check if a file is executable Programming language construct 1. a)if ..then.elsefi b)if..then..elif..elsefi 2. for..dodone 3. while..do..done 4. caseesac 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. Syntax: If condition 10
Then Commands Else Commands fi Eg. If(grep India countri.dat) Then Echo pattern found Else Echo pattern not found fi 2) for construct : used to perform same set of operations on a list of values. Syntax: For variable in value1 value2 value3 Do Commands Eg. 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. Syntax: While condition Do Command list Done Eg: to print 3 numbers A=1 While [4a le 3] Do Echo $a A=expr $a+1 Done 4) Case construct : Its useful for executing a set of commands based on the choices given by the user. Syntax: case value in choice 1) commands;; choice 2)commands;; . 11
Case 4myval in 0) echo zero;; 1) echo one;; 2) echo two;; 3) echo three;; *) echo invalid argument;; esac
12
SHELL PROGRAMMING I Ex.No :2A Aim: To write a shell program to perform addition of two numbers. Algorithm: 1.Read the two numbers. 2.Add the two numbers. 3.Display the result. Program //Shell Program for addition of two numbers echo "Enter the value of A " read a echo "Enter the value of B " read b c=`expr $a \+ $b` echo "The sum of $a+$b=$c" Output: $ sh add.sh Enter the value of A 10 Enter the value of A 20 The sum of 10+20=30 Addition of Two numbers
Result: Thus, the shell program for addition of two numbers was executed and printed the result successfully.
13
Ex.No:2B Swapping of two numbers Aim: To write a shell program to swap two numbers without using temporary variable. Algorithm: 1. Enter the values a,b to swap. 2. Read the values of a and b. 3. Using following expression the values are swapped a=a+b; b=a-b; a=a-b; 4.Display the swapped values of a and b. Program: echo "Enter two numbers" read a b echo "Before swapping" echo "A=$a B=$b" a=`expr $a + $b` b=`expr $a - $b` a=`expr $a - $b` echo "After swapping" echo "A=$a B=$b"
output: $ sh swapping.sh Enter two numbers 78 34 Before swapping A=78 B=34 After swapping A=34 B=78
14
Result: Thus, the shell program to swap two numbers without using temporary variable is executed and verified sucussefully.
Ex.No:2C
Odd or Even
Aim: To write a shell program to check whether the given number is odd or even. Algorithm: 1.Read the input 2.Find the remainder value of n and store it into the variable c. 3.If it is equal to zero, print the given number is even number else it is odd number.
Program
//Shell program for Odd or Even number echo "Enter the N value" read n c=`expr $n \% 2` if test $c -eq 0 then echo "Even number" else echo "Odd number" fi Output: $sh odd.sh Enter the N value 10 Even number $sh odd.sh Enter the number 7 Odd number
15
Result: Thus, the shell program for ODD/EVEN has been executed and verified successfully.
Ex.No:2D Largest Of Three Numbers Aim: To write a shell program to find the largest of three numbers. Algorithm: 1.Read the three numbers. 2.Compare a is greater than b and c, if it is greater then print a is greater 3.Else compare b is greater than c, if it is greater then print b is greater. 4.Else print c is greater. Program //Shell Program for Largest of three numbers echo "Enter the first number" read a echo "Enter the second number" read b echo "Enter the third number" read c if test $a gt $b a $a gt $b then echo "The biggest number is $a" elif test $b -gt $c then echo "The biggest number is $b" else echo "The biggest number is $c" fi Output: $ sh large.sh Enter the first number: 12 Enter the second number: 78 Enter the third number: 34 The biggest number is 78
16
Result Thus, the shell program for largest among three numbers was executed and printed the result successfully.
Ex.No:2E Students Performance Details Aim: To write a shell program to display students performance details using If-else statement. Algorithm: 1. Read the name of the student. 2. Read the student marks in five subjects. 3. calculate the total and average for the marks obtained. 4. Print the name, total and average. 5. Check if the average is greater than 75 then print Distinction.else go to step 5. 6. If average is greater than 60 then print first class.else go to step 6. 7. If the average is greater than 50 then print second class.else goto step 7. 8.if the average is below 50 print fail. Program echo "Enter the student name" read student_name echo "Enter student Marks" read sub1 sub2 sub3 sub4 sub5 total=`expr $sub1 + $sub2 + $sub3 + $sub4 + $sub5` average=`expr $total / 5` echo "The Student Name:$student_name" echo "The Total Marks:$total" echo "The Average Marks:$average" if [ $average -ge 75 ] then echo "Grade is Distinction" elif [ $average -ge 60 ] then echo "Grade is First Class" elif [ $average -ge 50 ] then echo "Grade is second class" else echo "Fail" fi Output: Enter the student name: manimozhi Enter student Marks: 87 98 89 67 79 17
The Student Name: manimozhi The Total Marks: 420 The Average Marks: 84 Grade is Distinction
Result: Thus, the shell program to display student performance details is executed and verified successfully.
Ex.No:2F Arithmetic Operations Using CASE Aim: To write a shell program to perform all type of arithmetic operations such as addition, subtraction, etc. Algorithm: 1.Begin the program 2.Display message Enter two numbers 3.Read the first and second value in variable a and b 4.Display message Enter your choice 5.Display message Enter 1 for Addition 6.Display message Enter 2 for Subtraction 7.Display message Enter 3 for Multiplication 8.Display message Enter 4 fpr Division 9. Display message Enter 5 for Reminder 10.Display message 5. Exit 11.Read the value in variable choice 12 . Look at variable choice using case command 13. if value of choice == 1 Compute c = value of a + value of b Display message The Sum is : and value of c 14. if value of choice == 2 Compute c = value of a - value of b Display message The difference is : and value of c 15. if value of choice == 3 Compute c = value of a * value of b Display message The Product id: and value of c 16. if value of choice == 4 Compute c = value of a / value of b Display message The Quotient is : and value of c 17. if value of choice == 5 Compute c = value of a % value of b Display message The Remainder is : and value of c 18. if value of choice == 5 exit 19. Stop the program 18
Program echo "Enter two numbers" read a b echo "Enter your choice" echo "Enter 1 for addition" echo "Enter 2 for subtraction" echo "Enter 3 for multiplication" echo "Enter 4 for division" read choice case "$choice" in 1) c=`expr $a + $b` echo "The sum is $c";; 2) c=`expr $a - $b` echo "The difference is $c";; 3) c=`expr $a /* $b` echo "The product is $c";; 4) c=`expr $a / $b` echo "The quotient is $c";; 5) c=`expr $a % $b` echo "The reminder is $c";; *) echo "Invalid choice";; esac Output: $ sh scase.sh Enter two numbers 5 4 Enter your choice Enter 1 for addition Enter 2 for subtraction Enter 3 for multiplication Enter 4 for division Enter 5 for reminder 3 The product is 20
Result: Thus, the shell program for arithmetic operations using CASE was executed and printed the result successfully. 19
Ex.No:2G Aim:
Sum of Series
To write a shell program to print the sum of series. Algorithm: 1.Read the input value. 2.Assign sum=o and I=1 3.Repeat the steps 4 until I value is greater than n. 4.Add sum and i value and store it in summand then increment the I value. 5.Display the result. Program //Sum of series 1+2+3+.+N echo "Enter the value of N" read n sum=0 i=1 until [ $i -gt $n ] do sum=`expr $sum \+ $i` i=`expr $i + 1` done echo "The Sum of the series :$sum" Output: $ sh sum.sh Enter the value of N 5 The Sum of the series :15
Result: Thus, the shell program for sum of series was executed and printed the result successfully. 20
Ex.No:2H Calculate the value of X n Aim: To write a shell program to swap calculate the value of X n. Algorithm: 1. Enter the values of a and b. 2. Read the values of a and b. 3. Assign i=1,s=1. 4. Check the condition whether i<b. 5. If step 4 is true do the following expressions. s=s*a. i=i+1. 6. Repeat step 5 until step 4 becomes false. 7. Display the values of s. Program: echo "Enter the value of x" read a echo "Enter the value on n" read b s=1 i=1 while [ $i -le $b ] do s=`expr $s \* $a` i=`expr $i + 1` done echo "The value of $a powers $b is $s" Output: $ sh power.sh Enter the value of x: 2 Enter the value on n: 3 The value of 2 powers 3 is 8 [idhaya@linuxserver ~]$ sh power.sh Enter the value of x: 5 Enter the value on n: 6 The value of 2 powers 3 is 15625
Result: Thus, the shell program to calculate the value of X n is executed and verified successfully
21
Ex.No.2I Aim:
To write a shell program to find the factorial value of a given number. Algorithm: 1.Read the value of n. 2.Assign n to temporary variable and fact =1. 3.Check n is greater than 0 if it is true then repeat the step 4 until the n value is equal to 0. 4.Multiply fact with n and assign the result to the variable fact and decrement the value of n. 5.Print the result.
Program //Shell Program for Factorial of N Numbers echo "Enter the value of N:" read n i=$n; fact=1 while [ $n -gt 0 ] do fact=`expr $fact \* $n` n=`expr $n \- 1` done echo "The factorial of $i is $fact" Output: $ sh fact.sh Enter the value of N: 5 The factorial of 5 is 120
Result Thus, the shell program for factorial number was executed and printed the result successfully. 22
Ex.No:2J Aim:
Fibonacci Series
To write a shell program to print the Fibonacci series of a given number. Algorithm: 1.Read the input value. 2.Initialize the value of a=-1,b=1,j=0 3.Check j is less than n if it is true then repeat the steps 4,5 until the loop becomes false. 4.Add the value of a and b and store it in c 5.Print the c value. Then assign the b value to a and c value to b Program //Shell Program for Fibonacci number generation echo "Enter the value of N" read n a=-1 b=1 j=0 while [ $j -lt $n ] do c=`expr $a + $b` echo $c a=$b b=$c j=`expr $j + 1` done Output: $ sh fib.sh Enter the value of N
3 0 1 1
Result: Thus, the shell program for fibonacci series was executed and printed the result successfully. 23
Ex.No:2K Armstrong Number Aim: To write a shell program to check whether the given number is odd or even. Algorithm: 1.Start the program. 2.Read the value of num. 3. Initialize the value of variable sum. 4.Check the condition that num gt 0 then goto step 5 else goto step 9. 5.Calculate the variable of y num%10. 6. Calculate the variable of z y*y*y. 7. Calculate sum sum+z. 8. Calculate num num/10. 9. Check the condition whether x eq num. If yes then goto step 10 else goto step 11. 10. Print the given number is an armstrong number. 11. Print the given number is not an armstrong number. 12. Stop the program. Program echo "Enter a number" read num x=$num sum=0 while [ $num -gt 0 ] do y=`expr $num % 10` z=`expr $y \* $y \* $y` sum=`expr $sum + $z` num=`expr $num / 10` done if [ $x -eq $sum ] then echo "$x is an armstrong number" else echo "$x is not an armstrong number" fi Output: $ sh armstrong.sh Enter a number: 153 153 is an armstrong number
Result: Thus, the shell program for Armstrong number was executed and printed the result successfully.
24
Ex.No:2L Palindrome Aim: To write a shell program to find the given string is palindrome or not. Algorithm: 1. Enter the string. 2. Read the string. 3. calculate the length of the string. 4. Check whether the length of the string is greater than 0. 5. If step 4 is true do the following expression. temp=str|cut c $len. rev=print rev temp. len=len-1. 6.Print the reversed string in rev. 7. Check if str and rev are same if it is true print string is palindrome else print not Not a palindrome. Program echo "Enter the word" read str len=`echo $str|wc -c` while [ $len -gt 0 ] do temp=`echo $str|cut -c$len` rev=`echo $rev$temp` len=`expr $len - 1` done echo "The reversed string is $rev" if [ $str = $rev ] then echo "The given word is palindrome" else echo "The given word is not palindrome" fi Output: $ sh sreverse.sh Enter the word: madam The reversed string is madam The given word is palindrome $ sh sreverse.sh Enter the word: idhaya The reversed string is ayahdi The given word is not palindrome
Result: Thus, the shell program to find the given string is palindrome or not is executed and verified sucussefully. 25
C PROGRAMMING ON UNIX
Ex.No:3A Sorting of given numbers using function Aim: To write a C program in vi editor to sorting of given numbers using function. Algorithm: 1. Start the program. 2. Display message Enter the limit 3. Read the size of the element n. 4. Get the elements of array marks. 5. Print the elements of the array marks before sorting. 6. Call the function sort by passing its value sort(n.marks). 7. Print the elements of the array marks after sorting. Algorithm for the function sort(int m,int x[]) 1. Declare i,j,t as an integer variable. 2. If x[j-1] is greater than or equal to x[j] then assign the following t=x[j-1]; x[j-1]=x[j]; x[j]=t;
Program #include<stdio.h> int main() { int i,n; int marks[50]; printf("Enter the limit"); scanf("%d",&n); printf("Enter the numbers to sort"); for(i=0;i<n;i++) { scanf("%d",&marks[i]); } printf("Before sorting\n"); for(i=0;i<n;i++) printf("%d",marks[i]); printf("\n\n"); sort(n,marks); printf("After sorting\n"); for(i=0;i<n;i++) printf("%4d",marks[i]); printf("\n"); } 26
sort(m,x) int m,x[]; { int i,j,t; for(i=1;i<=m-1;i++) for(j=1;j<=m-i;j++) if(x[j-1]>=x[j]) { t=x[j-1]; x[j-1]=x[j]; x[j]=t; } } Output: [idhaya@linuxserver asr1]$ cc sort.c [idhaya@linuxserver asr1]$ ./a.out Enter the limit 5 enter the numbers to sort 78 23 98 23 99 Before sorting 78 23 98 23 99 After sorting 23 23 78 98 99
Result: Thus the C program in vi editor to sorting of given number has been executed and the output is verified. 27
Ex.No:3B Factorial using recursive function Aim: To write a C program in vi editor to find the factorial of a given number using recursive function. Algorithm: 1. Start the program. 2. Display message Enter the limit 3. Read the first value in variable n 4. Call the function recur(n) 5. Display message Factorial of given number is: and the value of a 6. Stop the program. Algorithm for the function recur: 1.if the num is 1 then return 1 2. Else return num*recur(num-1) to the main function Program #include<stdio.h> int main() { int n,a; clrscr(); printf("Enter the number:"); scanf("%d",&n); a=recur(n); printf("\nFactorial of the given number %d is %d",n,a); } int recur(int num) { int fact=1; if(num==1) return(1); else fact=num*recur(num-1); return(fact); } Output: $cc fact.c $./a.out Enter the number: 6 Factorial of the given number 6 is 720
Result: Thus the C program to find factorial using recursive function has been executed and the output is verified. 28
Ex.No:3C Swapping of two numbers using pointers Aim: To write a C program in vi editor to swap two numbers using pointers. Algorithm: 1.Begin the program 2.Display message Enter the values of x and y 3.Read the first and second value in variable x and y 4.Call the function change by passing by reference swap(&x,&y) 5.Print the values of the variables after swap 6.Stop the program Algorithm for the function change(int*a,int *b) 1.Declare k as an integer variable 2.Assign the following k=*a; *a=*b; *b=k; 3. Print the values of the variables after swap Program #include<stdio.h> main() { int x,y,change (int* , int*); printf("\n enter the values of x and y:"); scanf("%d%d",&x,&y); change(&x,&y); printf("\n In main() :x=%d y=%d",x,y); return 0; } change(int *a,int *b) { int k; k=*a; *a=*b; *b= k; printf("\n In Change() : x=%d y=%d",*a,*b); } Output: $cc swap.c $./a.out enter the values of x and y: 2 3 In main() :x=3 y=2 In Change() : x=3 y=2 Result: Thus the C program to swap two numbers using pointers has been executed and the output is verified. 29
Ex.No:3D Aim:
To write a C program in vi editor to store a character string in a block of memory space Created by malloc and then modify the same to store a large string. Algorithm: 1.Start the program. 2.Using malloc function create a memory space for file pointer buffer. 3.Print the size of the buffer. 4.Using Strcpy store a character string in a block of memory space allocated. 5. To modify the memory space use realloc function. 6. Using strcpy store the large string in a reallocated memory space. 7. Free the memory space allocated. 8. Stop the program. Program M , mm mm m
#include<stdio.h> #include<stddef.h> #define NULL 0 int main() { char *buffer; /*allocating memory*/ if((buffer=(char *)malloc(10))==NULL) { printf("malloc failed\n"); exit(1); } printf("buffer of size %d created\n",_msize(buffer)); strcpy(buffer,"HYDERBAD"); printf("\n buffer contains:%s\n",buffer); /* reallocation*/ if((buffer=(char*)realloc(buffer,15))==NULL) { printf("reallocation failed\n"); exit(1); } printf("\n buffer size modified\n"); printf("\n buffer still contains: %s\n",buffer); strcpy(buffer,"SECUNDERABAD"); printf("\n buffer now contains: %s\n",buffer); /*freeing memory*/ free(buffer); } 30
Output: $cc dynamic.c $./a.out Buffer of size 10 created Buffer contains:HYDERABAD Buffer size modified Buffer still contains:HYDERABAD Buffer now contains:SECUNDERABAD
31
Result: Thus the C program in vi editor to store a character string in a block of memory space Created by malloc and then modify the same to store a large string is excuted and verified. Ex.No:3E Read the contents of a File Aim: To write a C program to read the contents of a file. Algorithm: 1. Start the program. 2. Open the file in read mode. 3. If the file exist, read a character from the file and print. 4. Continue step 3 until end of file. 5. If the file does not exist then stop. 6. Stop the program. Program #include<stdio.h> int main() { FILE *fp; char c; printf("\n\t\tReading the contents of a file"); if((fp=fopen("sample.txt","r"))==0) printf("\n\t Contents of the file\n"); else { printf("\n\t cannot open the file"); do { putchar(c=getc(fp)); } while(c!='\n'); } fclose(fp); } Input: Sample.txt Welcome to IECW Output: Reading the contents of a file Contents of the file Welcome to IECW
Result: Thus the C program to read the contents of a file has been executed and the output is verified. 32
Ex.No:3F Aim:
To write a program to separate even and odd numbers using files. Algorithm: 1.Start the program. 2.Open a file pra.dat in write mode. 3.Input the numbers until end of file. 4.Close the file. 5.Open two files even.dat,odd.dat in write mode. 6.Open the file pra.dat in read mode. 7. Find the remainder of each number when divided by 2. 8. If it is zero copy the number in even.dat else in odd.dat. 9. Repeat the steps 5& 6 until end of file. 10.Close the files. 11. Open the files even.dat and odd.dat in read mode. 12. read the contents of the file and print them. 13.Repeat step 12 until end of file. 14.Close the files. 15. Stop the Program. Program #include<stdio.h> int main() { FILE *fp,*fpo,*fpe; int c,d; fp=fopen("pra.dat","w"); printf("\n\t Enter the numbers"); while((scanf("%d",&c))!=EOF) putw(c,fp); fclose(fp); fp=fopen("pra.dat","r"); fpe=fopen("even.dat","w"); fpo=fopen("odd.dat","w"); while((c=getw(fp))!=EOF) { d=c%2; if(d==0) putw(c,fpe); else putw(c,fpo); } fclose(fp); fclose(fpo); fclose(fpe); fpe=fopen("even.dat","r"); printf("\n the Even Numbers are"); while((c=getw(fpe))!=EOF) 33
printf("\n%d",c); fclose(fpe); fpo=fopen("odd.dat","r"); printf("\n The odd Numbers are"); while((c=getw(fpo))!=EOF) printf("\n%d",c); fclose(fpo); } Output: $cc feo.c $./a.out File handling pra.dat 1 6 3 16 10 19 21 24 23 100 even.dat 6 16 10 24 100 odd.dat 1 3 19 21 23 The even numbers are 6 16 10 24 100 The odd numbers are 1 3 19 21 23
Result: Thus, the program to separate even and odd numbers using files is executed and verified successfully. 34