In: Computer Science
Rewrite the attached code program using read, write, open and close (System I/O functions) instead of the standard I/O functions. Also please write comments explaining each line of code clearly and concisely please.
#include
#include
int main(int argc, char *argv[])
{ FILE *fd;
   char c;
   if(argc==1)
   fd=stdin;
   else
        if((fd = fopen(argv[1],
"r"))==NULL){
       fprintf(stderr, "Error opening %s,
exiting\n", argv[1]);       
    exit(0);
   }
   while( (c=getc(fd)) != EOF)
   putc(c, stdout);
   exit(0);
}
SOLUTION
#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>
//string.h to have the string methods
int main(int argc, char *argv[])
{
int fd;
//here in system calls we will defimee the file descriptor fd
unilike the File pointer in the
// here fd has three paramets 0- input,1- output 2- standard
error
char c;
if(argc==2)
{
   //open the first file in the read, write mode and
check if file is opened successfully or not if not exit from the
program
       fd = open(argv[1], O_RDWR);
       //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);
        }
       
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);
       }
       //write data to the file(write
takes 3 paramets same as read )
       
write(fd,"Hello",strlen("HelloS"));
       while(read(fd,&c,1)!=0){
           
printf("%c",c);
       }
   }
   //close the file
close(fd);
}

OUTPUT
This is the output after running the program two times so it has two hello inserts

FIle:
