Anda di halaman 1dari 32

BASIC UNIX COMMANDS

1 cat
cat" is short for concatenate. This command is used to create, view and concatenate files.
Syntax: cat [argument] [specific file] Examples: cat /etc/passwd This command displays the "/etc/passwd" file on your screen. cat /etc/profile This command displays the "/etc/profile" file on your screen. Notice that some of the contents of this file may scroll off of your screen. cat file1 file2 file3 > file4 This command combines the contents of the first three files into the fourth file.

2 pwd
"pwd" stands for print working directory. It displays your current position in the UNIX filesystem.
Syntax: pwd [username] Examples: pwd There are no options (or arguments) with the "pwd" command. It is simply used to report your current working directory.

3 man
man stands for manual. It shows the information about any command.
Syntax: man (command)

4 ls
"ls" stands for list. It is used to list information about files and directories.
Syntax: ls [options] [names] Examples: ls This is the basic "ls" command, with no options. It provides a very basic listing of the files in your current working directory. Filenames beginning with a decimal are considered hidden files, and they are not shown. ls -a The -a option tells the ls command to report information about all files, including hidden files. ls -l The -l option tells the "ls" command to provide a long listing of information about the files and directories it reports. The long listing will provide important information about file permissions, user and group ownership, file size, and creation date. ls -al This command provides a long listing of information about all files in the current directory. It combines the functionality of the -a and -l options. This is probably the most used version of the ls command. ls -al /usr This command lists long information about all files in the "/usr" directory. ls -alR /usr | more This command lists long information about all files in the "/usr" directory, and all sub-directories of /usr. The -R option tells the ls command to provide a recursive listing of all files and sub-directories. ls -ld /usr Rather than list the files contained in the /usr directory, this command lists information about the /usr directory itself (without generating a listing of the contents of /usr). This is very useful when you want to check the permissions of the directory, and not the files the directory contains.

5 rm
The "rm" command is used to remove files and directories. (Warning - be very careful when removing files and directories!)
Syntax: rm [options] files Options: -d, --directory unlink FILE, even if it is a non-empty directory (super-user only) -f, --force ignore nonexistent files, never prompt -i, --interactive prompt before any removal -r, -R, --recursive remove the contents of directories recursively -v, --verbose explain what is being done Examples: rm Chapter1.bad This command deletes the file named "Chapter1.bad" (assuming you have permission to delete this file). rm Chapter1 Chapter2 Chapter3 This command deletes the files named "Chapter1", "Chapter2", and "Chapter3". rm -i Chapter1 Chapter2 Chapter3 This command prompts you before deleting any of the three files specified. The -i option stands for inquire. You must answer y (for yes) for each file you really want to delete. This can be a safer way to delete files. rm *.html This command deletes all files in the current directory whose filename ends with the characters ".html". rm index* This command deletes all files in the current directory whose filename begins with the characters "index". rm -r new-novel This command deletes the directory named "new-novel". This directory, and all of its' contents, are erased from the disk, including any sub-directories and files.

6 mv
The "mv" command is used to move and rename files.
Syntax: mv [options] sources target Options: -b backup files that are about to be overwritten or removed -i interactive mode; if dest exists, you'll be asked whether to overwrite the file Examples: mv Chapter1 Chapter1.bad This command renames the file "Chapter1" to the new name "Chapter1.bad". mv Chapter1 garbage This command renames the file "Chapter1" to the new name "garbage". (Notice that if "garbage" is a directory, "Chapter1" would be moved into that directory). mv Chapter1 /tmp This command movesj the file "Chapter1" into the directory named "/tmp". mv tmp tmp.old Assuming in this case that tmp is a directory, this example renames the directory tmp to the new name tmp.old.

7 cp
The "cp" command is used to copy files and directories.
Syntax: cp [options] file1 file2 cp [options] files directory Options: -b backup files that are about to be overwritten or removed -i interactive mode; if dest exists, you'll be asked whether to overwrite the file -p preserves the original file's ownership, group, permissions, and timestamp Examples: cp .profile .profile.bak This command copies your ".profile" to a file named ".profile.bak".

cp /usr/fred/Chapter1 This command copies the file named "Chapter1" in the "/usr/fred" directory to the current directory. This example assumes that you have write permission in the current directory. cp /usr/fred/Chapter1 /usr/mary This command copies the "Chapter1" file in "/usr/fred" to the directory named "/usr/mary". This example assumes that you have write permission in the "/usr/mary" directory.

8 passwd
"passwd" stands for password. It is used to change the password of the user.
Syntax: passwd [username] Examples: passwd This command is used to change the password of the current user. (Current) unix password:******** new unix password: ******* retype new unix password:******* Note: The password that is typed is not visible. passwd root This command is used to change the password of the user root.

9 who am i
who am i command is used to know about your login details.
Syntax: who am i

10 who or w
who" or w commands are used to know the users logged in the system.
Syntax: w

11 kill
kill command ends one or more process IDs. In order to do this you must own the process or be designated a privileged user. To find the process ID of a certain job use ps.
Syntax: kill [options] IDs

12 mkdir
"mkdir" command is used to create directoriess.
Syntax: mkdir [options] directory-name Examples: mkdir tmp This command creates a new directory named "tmp" in your current directory. (This example assumes that you have the proper permissions to create a new subdirectory in your current working directory.) mkdir memos letters e-mail This command creates three new sub-directories (memos, letters, and e-mail) in the current directory. mkdir /usr/fred/tmp This command creates a new directory named "tmp" in the directory "/usr/fred". "tmp" is now a sub-directory of "/usr/fred". (This example assumes that you have the proper permissions to create a new directory in /usr/fred.) mkdir -p /home/joe/customer/acme This command creates a new directory named /home/joe/customer/acme, and creates any intermediate directories that are needed. If only /home/joe existed to begin with, then the directory "customer" is created, and the directory "acme" is created inside of customer.

13 rmdir
The "rmdir" command is used to remove directories.
Syntax: rmdir [options] directories Examples: rm Chapter1.bad This command deletes the file named "Chapter1.bad" (assuming you have permission to delete this file). rm Chapter1 Chapter2 Chapter3 This command deletes the files named "Chapter1", "Chapter2", and "Chapter3". rm -i Chapter1 Chapter2 Chapter3 This command prompts you before deleting any of the three files specified. The -i option stands for inquire. You must answer y (for yes) for each file you really want to delete. This can be a safer way to delete files.

rm *.html This command deletes all files in the current directory whose filename ends with the characters ".html". rm index* This command deletes all files in the current directory whose filename begins with the characters "index". rm -r new-novel This command deletes the directory named "new-novel". This directory, and all of its' contents, are erased from the disk, including any sub-directories and files.

14 cd or chdir
"cd" stands for change directory. It is the primary command for moving around the filesystem.
Syntax: cd [name of directory you want to move to] Examples: cd /usr This command moves you to the "/usr" directory. "/usr" becomes your current working directory. cd /usr/fred Moves you to the "/usr/fred" directory. cd /u*/f* Moves you to the "/usr/fred" directory - if this is the only directory matching this wildcard pattern. cd Issuing the "cd" command without any arguments moves you to your home directory. cd Using the Korn shell, this command moves you back to your previous working directory. This is very useful when you're in the middle of a project, and keep moving back-and-forth between two directories.

15 ps
"ps" command (process statistics) lets you check the status of processes that are running on your Unix system.
Syntax: ps [options] Examples: ps The ps command by itself shows minimal information about the processes you are running. Without any arguments, this command will not show information about other processes running on the system. ps -f The -f argument tells ps to supply full information about the processes it displays. In this example, ps displays full information about the processes you are running. ps -e The -e argument tells the ps command to show every process running on the system. ps -ef The -e and -f arguments are normally combined like this to show full information about every process running on the system. This is probably the most often-used form of the ps command. ps -ef | more Because the output normally scrolls off the screen, the output of the ps -ef command is often piped into the more command. The more command lets you view one screenful of information at a time. ps -fu fred This command shows full information about the processes currently being run by the user named fred (the -u option lets you specify a username).

16 stty
stty" command is used to set the terminal characteristics. Terminal is device with which a user communicates with system.
Syntax: stty Options: -a displays the current settings

17 tty
tty" command is used to know the terminal details.
Syntax: tty

18 uname
"uname" command tells the machine in the network.
Syntax: uname [options] Examples: uname -n

19 date
date command displays the system date.
Syntax: date Options: Date can be displayed in different formats with the symbol % Examples: date +%n Displays the month name. date +%m Displays the number of month.

20 clear
"clear" command is used to clear the screen.
Syntax: clear

21 cal
cal stands for calendar. It displays the calendar of the year or month.
Syntax: cal [arg1] [arg2] Examples: cal If cal command is used without any argument, it displays the calendar of the current month. cal 2008 If cal command is used with one argument, it displays the calendar of the year. In this example, the year is 2008. cal 6 2007 If cal command is used with two arguments, it displays the calendar of month in that year. In this example, the month is 6 and year is 2007.

22 bc
"bc" command is used to enter into calculator, to do any simple or complex operations. To quit the calculator, use Ctrl+d.
Syntax: bc

23 factor
"factor" command is used to factorize a number and displays its prime factors. To quit the application, type q. Largest number that can be taken is 246 (7.2e13)
Syntax: factor Examples: factor 30 2 3 5 q

24 type
"type" command is used to locate the command file.
Syntax: type (command) Example: type ls /bin/ls

25 touch
"touch" command is used to change the time stamps. If the file does not exists, then a new file is created.
Syntax: touch [option] [expression] filename

26 df
"df" command is used to check free disk space.
Syntax: df

27 du
"du" command is used to check disk utilization.
Syntax: du

28 ln
ln command is used to create linked files.
Syntax: ln file1 file2 [file3 [file4 [.] ] ]

29 chmod
chmod command is used to change the file permissions of files and folders.
Syntax: chmod (permissions) files Examples: There are two types of modes that can be given for permissions. chmod 777 filename This command gives all the permissions to the file. chmod u+x filename This command gives execute permission to the user on the file. chmod a-r filename This command removes the read permission to all the users on the file.

30 umask
umask command is used to check and set the default file and folder permissions. The umask setting can be changed only by the administrator.
Syntax: umask [permissions] Examples: umask This command displays the default file permissions when created. umask 022 This command removes the permissions from the default permissions existing.

31 chown and chgrp


chown stands for change owner, chgrp stands for change group. These commands changes the file ownerships.
Syntax: chown [user] filename chgroup [user] filename

32 grep
Think of the "grep" command as a "search" command. It is used to search for text strings within one or more files.
Syntax: grep [options] regular expression [files] Options: -i case-insensitive search -n show the line# along with the matched line -v invert match, e.g. find all lines that do NOT match -w match entire words, rather than substrings Examples: grep 'fred' /etc/passwd This command searches for all occurrences of the text string 'fred' within the "/etc/passwd" file. It will find and print (on the screen) all of the lines in this file that contain the text string 'fred', including lines that contain usernames like "fred" - and also "alfred". grep '^fred' /etc/passwd This command searches for all occurrences of the text string 'fred' within the "/etc/passwd" file, but also requires that the "f" in the name "fred" be in the first column of each record (that's what the caret character tells grep). Using this moreadvanced search, a user named "alfred" would not be matched, because the letter "a" will be in the first column. grep 'joe' * This command searches for all occurrences of the text string 'joe' within all files of the current directory.cp /usr/fred/Chapter1 This command copies the file named "Chapter1" in the "/usr/fred" directory to the current directory. This example assumes that you have write permission in the current directory.

33 cmp
cmp command compares two files and displays the difference.
Syntax: cmp [options] file1 file2

34 diff
diff command compares two files and displays the changes so as to make both files equal.
Syntax: diff [options] file1 file2

35 comm
comm command compares two files and displays the unique lines in each file and common lines in both the files.
Syntax: comm [options] file1 file2

36 more
more command is used for paging output.
Syntax: more file1 [files] Internal Commands of more: <space> <Enter> b or [n]b = q h One page forward One line forward One or n pages backward Displays current line number Quit Help

37 wc
wc command is used for Line, Word or Character count of one or more files.
Syntax: wc [options] file1 [files] Options: -l -w -c Examples: wc l file1 This command displays the number of lines in the file file1. shows number of lines shows number of words shows number of characters

38 head
head displays the first n lines of the file.
Syntax: head [-lines] filename Examples: head file1 head command without number of lines displays first 10 lines of the file. head -5 file1 head command with number of lines displays first n lines of the file. Here number is 5.

39 tail
tail displays the last n lines of the file.
Syntax: tail [-lines] filename Examples: tail file1 head command without number of lines displays last 10 lines of the file. tail -3 file1 head command with number of lines displays last n lines of the file. Here number is 3.

40 cut
cut command cuts the file vertically.
Syntax: cut [options] filename Options: -c -f -d cutting by column cutting by field cutting by delimiter

41 paste
paste command joins two files vertically.
Syntax: paste [options] files

42 join
join command joins two files by a common column.
Syntax: join [options] files

43 sort
"sort" command is a filtering command used for ordering file. The original file will not be changed.
Syntax: sort [options] filename Options: -u -m -n Examples: sort file1 This command sorts the contents and displays the sorted output. sort file1 file2 file3 This command sorts multiple files. sort -3 file1 This command stops sorting after 3rd field. sort +3 file1 This command starts sorting after skipping 3rd field. sorts the files by removing the duplicate lines. merges two or more sorted files sorts numerically

44 banner
banner command prints message in large letters.
Syntax: banner [text]

45 lp
lp command sends the users print job to print queue.
Syntax: lp [options] files

DESCRIPTION ABOUT SHELLS


Why Use Shells?
Well, most likely because there is a simple way to string together a bunch of UNIX commands for execution at any time without the need for prior compilation. Also because its generally fast to get a script going. Not forgetting the ease with which other scripters can read the code and understand what is happening. Lastly, they are generally completely portable across the whole UNIX world, as long as they have been written to a common standard.

The Shell History:


The basic shells come in three main language forms. These are (in order of creation) sh, csh and ksh. Be aware that there are several dialects of these script languages which tend to make them all slightly platform specific. Where these differences are known to cause difficulties I have made special notes within the text to highlight this fact. The different dialects are due, in the main, to the different UNIX flavours in use on some platforms. All script languages though have at their heart a common core which if used correctly will guarantee portability.

Bourne Shell:
Historically the sh language was the first to be created and goes under the name of The Bourne Shell. It has a very compact syntax which makes it obtuse for novice users but very efficient when used by experts. It also contains some powerful constructs built in. On UNIX systems, most of the scripts used to start and configure the operating system are written in the Bourne shell. It has been around for so long that is it virtually bug free. I have adopted the Bourne shell syntax as the defacto standard within this book.

C Shell:
Next up was The C Shell (csh), so called because of the similar syntactical structures to the C language. The UNIX man pages contain almost twice as much information for the C Shell as the pages for the Bourne shell, leading most users to believe that it is twice as good. This is a shame because there are several compromises within the C Shell which makes using the language for serious work difficult (check the list of bugs at the end of the man pages!). True, there are so many functions available within the C Shell that if one should fail another could be found. The point is do you really want to spend your time finding all the alternative ways of doing the same thing just to keep yourself out of trouble. The real reason why the C Shell is so popular is that it is usually selected as the default login shell for most users. The features that guarantee its continued use in this arena are aliases, and history lists. There are rumours however, that C Shell is destined to be phased out, with future UNIX releases only supporting sh and ksh. Differences between csh and sh syntax will be highlighted where appropriate.

Korn Shell:
Lastly we come to The Korn Shell (ksh) made famous by IBM's AIX flavour of UNIX. The Korn shell can be thought of as a superset of the Bourne shell as it contains the whole of the Bourne shell world within its own syntax rules. The extensions over and above the Bourne shell exceed even the level of functionality available within the C Shell (but without any of the compromises!), making it the obvious language of choice for real scripters. However, because not all platforms are yet supporting the Korn shell it is not fully portable as a scripting language at the time of writing. This may change however by the time this book is published. Korn Shell does contain aliases and history lists aplenty but C Shell users are often put off by its dissimilar syntax. Any sh syntax element will work in the ksh without change.

SOLUTIONS FOR PROGRAMS


WEEK 1 Session 1 1. 2. 3. 4. 5. Sol: 1. 2. $ login: <user name> $ password: ****** $ vi ~ Unix is Case Sensitive ~ Never leave the Computer without logging out when you are working in a time sharing or network environments. Type <Esc> : wq <filename> $ logout 1. 2. 3. 4. 5. 6. 7. Sol: 1. 2. 6. 7. $ login: <user name> $ password: ****** $ vi myfile :wq $ logout Log into the system Open the file created in session 1 Add some text Change some text delete some text Save the changes Logout of the system Log in to the system Use Vi editor to create a file called myfile.txt which contain some text. Correct typing errors during creation Save the file Logout of the file

3. 4. 5. Session 2

WEEK 2 Log into the system Use the cat command to create a file containing the following data. Call it mutable use tabs to separate the fields 1425 4320 6830 1450 ravi ramu sita raju 15.65 26.27 36.15 21.86

a. use the cat command to display the file, my table b. use the vi command to correct any errors in the file, my table c. use the sort command to sort the file my table according to the first field. Call the sorted file my table(same name) d. print the file my table e. use the cut & paste commands to swap fields 2 and 3 my table. Call it mytable(same name) f. print the new file, my table g. logout of the system Sol: $ login: <user name> $ password:****** $ cat c1-14 1425 <tab> 4320 <tab> 6830 <tab> 1450 <tab> a. $ cat myfile $who|more c. $ sort +0 -1 mytable or $ sort o mytable mytable d. $ cat myfile e. $ cut f1 mytable >a $ cut f2 mytable >b $ cut f3 mytable >c $ paste a c b >mytable ravi <tab> ramu <tab> sita <tab> raju <tab> 15.65 <tab> 26.27 <tab> 36.15 <tab> 21.86 <tab>

f. $ cat mytable

WEEK 3 a. log in the system b. use the appropriate commands to determine your login shell c. use the /etc/passwd file to verify the result of step b. d. use the who command redirect the result to a file called myfile1.Use the more command to see the contents of myfile1. e. Use the date and who commands in sequence ?(in one line) such that the output of date will display on the screen and the output of who will be redirected to a file called my file2.Use the more command to check the contents of myfile2. f. write a sed command that deletes the second character in each line in a file g. write a sed command that deletes the character before the last character in each line in a file. h. write a sed command that swaps the first and second words in each line in a file Sol: a. b. c. d. e. f. g. h. $ login: <user name> $ password:****** $ echo $SHELL /bin/bash $ cat /etc/passwd $ who >| myfile1 $ more myfile1 $ date; who >myfile2 $ more myfile2 $ cat >myfile3 $ sed "s/^\(.\)./\1/" myfile3 $ sed "s/.\(.\)$/\1/" myfile3 or $ sed s/\([a-z].*\).\(.$\)/\1\2/ myfile3

$ sed "s/ *[^ ]*\( *[^ ]*\)$/\1/" myfile3 or $ sed s/\[a-z]*\) \([a-z]*\)/\2\1 myfile3

WEEK 4 a) Pipe your /etc/passwd file to awk and print out the home directory of each user. b) Develop an interactive grep script that asks for a word and a file name and then tells how many lines contain that word c) Repeat d) Part using awk Sol: a. $ cat /etc/passwd | awk f scr.awk >awk1 scr.awk BEGIN {FS = /} { print($5) $ more awk1 b. $ cat >pp a.sh echo \n Enter the word: read pname echo \n Enter the filename: read file echo \n The number o lines that contain: $pname is: grep c $pname $file $ sh a.sh c. ds.awk BEGIN {count=0; x=$pname} /x/{count++} a.sh echo \n Enter the word: read pname echo \n Enter the filename: read file echo \n The number of lines that contain: $pname is: awk f ds.awk $file d. $ awk {print $NF} n1 e. $ awk $3 > 5 && $4 != 0 {print} n1 awk2 BEGIN { print The Begin} { if (($3 > 5 && $4 != 0)) { print $0 } } END { print The End} (or)

$ awk f awk2 n1 WEEK 5 a) Write a shell script that takes a command line argument and reports on whether it is directory, a file, or something else b) Write a shell script that accepts one or more file name as a arguments and converts all of them to uppercase, provided they exits in the current directory c) Write a shell script that determines the period for which a specified user is working on the system Sol: a. echo "Enter a file name:" read file if [[ -f $file ]] then echo "File" elif [ -d $file ] then echo "Directory" elif [ -s $file ] then echo "Special file" else echo "File not found" fi b. echo Enter no. of arguments you want to enter as filename read n ((i = 1)) if [[ $n > 0 ]] then while [[ $i <= $n ]] do echo enter filename read fname if (ls | grep $fname) then tr [a-z] [A-Z] < $fname else echo file entered does not exist fi (( i = $i + 1 )) done else echo enter arguments must be positive fi

WEEK 6 (a) Write a shell script that accepts a file name starting and ending line numbers as arguments and displays all the lines between the given line numbers (b) Write a shell script that deletes all lines containing a specified word in one or more files supplied as arguments to it. Sol: a. s.sh
if [[ -s $1 ]] then head -$3 $1 | tail + $2 else echo file does not exist fi

$ sh s.sh fact 2 6 b. l.sh echo Enter no. of files: read n (( i = 1 )) if (( $n > 0 )) then while (( $i <= $n )) do echo Enter filename: read fname if [[ -f $fname ]] then sed /manager/d $fname else echo given file does not exist fi (( i = $i + 1 )) done else echo no. of arguments must be positive fi $ sh l.sh

WEEK 7 a) Write a shell script that computes the gross salary of a employee according to the following (i) if basic salary is <1500 then HRA 10% of the basic and DA =90% of the basic (ii) if basic salary is >1500 then HRA 500 and DA =98% of the basic The basic salary is entered interactively through the key board (b)Write a shell script that accepts two integers as its arguments and computes the value of first number raised to the power of the second number Sol: a. s1.sh echo " Enter Basic Salary " read bs
(( i = $bs / 100 )) if [[ $bs < 1500 ]] then (( hra = 10 \* $i )) (( da = 90 \* $i )) else (( hra = 500 )) (( da = 98 \* $i )) fi (( total = $bs + $hra + $da ))

echo Gross Salary = $total $ sh s1.sh b. s2.sh echo Enter 2 integers: read a b (( pow = 1 )) (( i = 1 )) while (( $i <= $b )) do (( pow = $pow \* $a )) (( i = $i + 1 )) done echo Computed value is : $pow $ sh s2.sh

WEEK 8 (a) Write an interactive file handling shell program. Let it offer the user the choice of copying ,removing ,renaming or linking files. Once the use has made a choice, have the program ask the user for necessary information, such as the file name ,new name and so on. (b) Write a shell script that takes a login name as command line argument and reports when that person logs in (c) Write a shell script which receives two files names as arguments. It should check whether the two file contents are same or not. If they are same then second file should be deleted. Sol: echo "Enter a File Name:" read f1 echo "Enter another File Name:" read f2 d=`cmp $f1 $f2` d1="" if [ $d -eq $d2 ] then echo "Two Files are similar and $f2 is deleted" rm $f2 else echo "Two Files differ each other" fi

WEEK 9 (a) Write a shell script that displays a list of all files in the current directory to which the user has read write and execute permissions (b) Develop an interactive script that asks for a word and file name and then tells how many times that word occurred in the file. (c) Write a shell script to perform the following string operations. 1) To extract a sub string from a given string 2) To find the length of a given string Sol: (a) # File Name : list.sh #!/bin/bash read -p "Enter a directory name : " dn if [ -d $dn ]; then printf "\nFiles in the directory $dn are :\n" for fn in `ls $dn` do if [ -d $dn/$fn ]; then printf "<$fn> Directory " elif [ -f $dn/$fn ] then printf "$fn File " fi if [ -r $dn/$fn ]; then printf " Read" fi if [ -w $dn/$fn ];then printf " Write" fi if [ -x $dn/$fn ];then printf " Execute" fi printf "\n" done else printf "\n$dn not exists or not a directory" fi

(b)

# File Name : wcount.sh #!/bin/bash read -p "Enter a file name : " fn if test -f $fn then echo "The contents of the file $fn is :" cat $fn echo "No. of Line : `wc -l $fn`" echo "No. of Words : `wc -w $fn`" echo "No. of Characters: `wc -c $fn`" else echo "$fn is not exists or not a file" fi print Enter the String:\c read strIn strlen=${# strIn} print the string length is : $strlen $ strlen.scr Enter the String: Now is the time The String length : 15

(c)

O/P:

WEEK 10
Write a C program that takes one or more file or directory names as command line input and reports the following information on the file. 1. 2. 3. 4. file type number of links read, write and execute permissions time of last access

(Note: use /fstat system calls) Sol: #include<stdio.h> main() { FILE *stream; int buffer_character; stream=fopen(test,r); if(stream==(FILE*)0) { fprintf(stderr,Error opening file(printed to standard error)\n); fclose(stream); exit(1); } if(fclose(stream))==EOF) { fprintf(stderr,Error closing stream.(printed to standard error)\n); exit(1); } return(); }

WEEK 11
Write C program that simulate the following unix commands (a) mv (b) cp Sol: /* File Name : bspace1.c */ #include<fcntl.h> #include<unistd.h> #include<stdio.h> main(int argc,char *argv[]) { FILE *fp; char ch; int sc=0; fp=fopen(argv[1],"r"); if(fp==NULL) printf("unable to open a file",argv[1]); else { while(!feof(fp)) { ch=fgetc(fp); if (ch== ' ') sc++; } printf("no of spaces %d",sc); printf("\n"); fclose(fp); } }

WEEK 12
Write a c program that simulates ls command (Use system calls /directory API) Sol: #include<stdio.h> #include<fcntl.h> #include<stdlib.h> main(int argc,char *argv[]) { int fd,i; char ch[1]; if (argc<2) { printf("Usage: mycat filename\n"); exit(0); } fd=open(argv[1],O_RDONLY); if(fd==-1) printf("%s is not exist",argv[1]); else { printf("Contents of the file %s is : \n",argv[1]); while(read(fd,ch,1)>0) printf("%c",ch[0]); } close(fd); }

Anda mungkin juga menyukai