RTS-2 3
RTS-2 3
Experiment: 2.3
Aim: Write a program to simulate UNIX Commands like ls, grep, etc.
Description:
The grep filter searches a file for a particular pattern of characters, and displays all lines that contain that
pattern. The pattern that is searched in the file is referred to as the regular expression (grep stands for global
search for regular expression and print out).
Before seeing the program, you have to learn about what is the meaning of the following commands.
cp- copy- it is used to copying contents from one file to another file.
Algorithm:
cp Source Destination
Syntax:
ls
grep-The grep filter searches a file for a particular pattern of characters, and displays all lines that contain that
pattern.
Import the necessary libraries for reading the contents of a directory, such as dirent.h and stdio.h.
Create a main function and declare a pointer to a DIR structure, which will be used to access the
contents of the directory.
Use the opendir function to open the current directory (represented by ".").
Use the readdir function in a loop to read the contents of the directory one by one.
Syntax:
Options Description
Import the necessary libraries for reading a file and processing its contents, such as stdio.h, string.h, and
stdlib.h.
Create a main function and declare a variable to hold each line of the file as it is read, as well as a
variable to hold the search string passed as a command-line argument.
Check if the required number of command-line arguments have been provided (at least two: the search
string and the name of the file). If not, print an error message and return an error code.
Use the fopen function to open the file with the specified name.
Check if the file was successfully opened. If not, print an error message and return an error code.
Use the fgets function in a loop to read the contents of the file one line at a time.
Use the strstr function to search each line for the search string. If a match is found, print the line
number, the name of the file, and the line itself.
Use the fclose function to close the file when you are done reading its contents.
Implementation:
#include<stdio.h>
#include<stdlib.h>
int main(){
createf();
copyfun();
lsandgrep();
}
Output: