You are on page 1of 4

Operating System

Lab Journal 8

Student Name
AMMARA BABAR
Enrolment No.
01-235191-043
Class and Section
4B

Title: System Calls


Objectives: To write programs using system calls like read, write for file Manipulation and also to
implement some system calls like cat, dir, ls in LINUX..
Tools Used: Linux Ubuntu Terminal, gedit editor, VS Code

Task # 1: Write a program in C to demonstrate file copy operation. (cp)


Copy from one file and paste to another using system calls open, read and write.
Program:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#define buffsize 1024
int main()
{
int fd,fd1 ,l;
char buff[buffsize] ;

printf("Enter filename to open it for reading \n");


scanf("%s", buff);
fd=open(buff,O_RDONLY);
if(fd == -1)
{
printf("Failed to open file \n");
exit(0);
}
printf("Reading the data from file\n");
printf("Enter filename to open it reading \n");
scanf("%s", buff);
fd1=open(buff,O_CREAT | O_WRONLY,0600);
if(fd1== -1)
{
printf("Failed to open file ");
exit(0);
}
l=read(fd,buff,buffsize);
while (l >1)
{
write(fd1,buff,buffsize);

}
printf("copied successfully :\n");
close(fd);
close(fd1);
return(0);
}
Output:

Task # 2: Write a program in C to demonstrate file read operation from command line i.e cat
operation.
Copy from one file and paste on screen using system calls open, read and write.
Program:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#define buffsize 1024

int main()
{
int fd ,l;
char buff[buffsize] ;

printf("Enter filename to open it for reading \n");


scanf("%s", buff);
fd=open(buff,O_RDONLY);
if(fd == -1)
{
printf("Failed to open file \n");
exit(0);
}
printf("Reading data from file\n");

l=read(fd,buff,buffsize);
while (l >0)
{
write(1,buff,l);
l=read(fd,buff,buffsize);
}
close(fd);
return(0);
}
Output:

Task # 3: Write a program in C to implement ls or dir command.


Take a directory name from user, open it and display its contents using library dirent.h.
Program:
#include <stdio.h>
#include <dirent.h>
int main(void)
{
struct dirent *de;
DIR *dr = opendir(".");
if (dr == NULL)
{
printf("Cannot open current directory" );
return 0;
}
while ((de = readdir(dr)) != NULL)
printf("%s\n", de->d_name);

closedir(dr);
return 0;
}
Output:

Submission Date: Signature Ms Umarah Qaseem

For your help in 3rd task: For functions, algorithm and library help see the online lecture video that has
been provided to you. It covers this in detail.

You might also like