In: Computer Science
Rewrite the attached mycat.c program in 3 using read, write, open and close (System I/O functions) instead of the standard I/O functions.
#include<stdio.h> int main(int argc, char* argv[]) { FILE *fp; void filecopy(FILE *, FILE *); if (argc == 1) { filecopy(stdin, stdout); } else { while(--argc >0) { if ((fp = fopen(*++argv, "r")) == NULL) { printf("cat: can not open %s\n", *argv); return 1; } else { filecopy(fp, stdout); fclose(fp); } } } return 0; } void filecopy(FILE *ifp, FILE *ofp) { int c; while ((c = getc(ifp)) != EOF) { putc(c, ofp); } }
Se here is the changed prohram.
#include<stdio.h>
#include<fcntl.h>
//we need to import fcntl to give the modes of opening the files
like O_RDONLY
#include<stdlib.h>
#include<string.h>
//Main driver function
int main(int argc, char *argv[])
{
int fd;
//here in system calls we will definee the file descriptor fd
// here fd has three paramets 0- input,1- output 2- standard
error
char c;
if(argc==3)
{
//open the first file in the read only mode and check if file
is
// opened successfully or not if not exit from the program
fd = open(argv[1], O_RDONLY, 0);
//it is unable to open the file it will return -1
if((fd)==-1){
//Failed to open it will return the fd as -1
printf("\nError opening the file") ;
exit(1);
}
char buf1[100];
int idx = 0;
while(read(fd,&c,1)!=0){
//priint data read will return the number of items read
//(read takes 3 parameters 1->filedescriptor,2-> buffer to
store data,
// 3->number of items to be read)
printf("%c",c);
buf1[idx++] = c;
}
buf1[idx++] = '\0';
int fdw;
fdw = open(argv[2], O_CREAT); // create file if not present
close(fdw);
fdw = open(argv[2], O_WRONLY); // open file in write only
mode
//write data to the file(write takes 3 parameters
write(fdw, buf1, strlen(buf1));
close(fdw);
}
//close the file
close(fd);
}
Run the compiled code with two command line arguments a.txt and b.txt
The context of a.txt will be copied in b.txt.