AIM:
To write a C program to simulate basic Unix commands like ls,grep.
DESCRIPTION:
UNIX commands can be simulated in the high level language using Unix system calls and APIs available in the language. In addition, programming language construct can also be used to avail the UNIX commands.
EXERCISES:
- Simulation of ls command
ALGORITHM :
Step 1: Include necessary header files for manipulating directory.
Step 2: Declare and initialize required objects.
Step 3: Read the directory name form the user.
Step 4: Open the directory using opendir() system call and report error if the directory is not
available.
Step 5: Read the entry available in the directory.
Step 6: Display the directory entry ie., name of the file or sub directory.
Step 7: Repeat the step 6 and 7 until all the entries were read.
/* 1. Simulation of ls command */
#include
#include
main()
{
char dirname[10];
DIR *p;
struct dirent *d;
printf("Enter directory name ");
scanf("%s",dirname);
p=opendir(dirname);
if(p==NULL)
{
perror("Cannot find dir.");
exit(-1);
}
while(d=readdir(p))
printf("%s\n",d->d_name);
}
SAMPLE OUTPUT:
enter directory name iii
.
..
f2
f1
2. Simulation of grep command.
ALGORITHM:
Step 1: Include necessary header files.
Step 2: Make necessary declarations.
Step 3: Read the file name from the user and open the file in the read only mode.
Step 4: Read the pattern from the user.
Step 5: Read a line of string from the file and search the pattern in that line.
Step 6: If pattern is available, print the line.
Step 7: Repeat the step 4 to 6 till the end of the file.
/* 2. Simulation of grep command */
#include
#include
main()
{
char fn[10],pat[10],temp[200];
FILE *fp;
printf("\n Enter file name : ");
scanf("%s",fn);
printf("Enter the pattern to be searched : ");
scanf("%s",pat);
fp=fopen(fn,"r");
while(!feof(fp))
{
fgets(temp,1000,fp);
if(strstr(temp,pat))
printf("%s",temp);
}
fclose(fp);
}
SAMPLE OUTPUT:
enter file name: file4
enter the pattern to be searched: roll
roll no percentage grade
RESULT:
Thus C program was written to simulate some Unix Commands and it has been executed successfully.
3 comments:
have to write both the programs sir ?
Yes. One program for each Command.
yr yeh prgram run toh ho he nhi rahe
Post a Comment