In: Computer Science
Modify the bellow program by using only system calls to perform the task. These
system calls are open,read,write, and exit .Use text and binary files to test your programs.
#include <stdio.h>
void main(int argc,char **argv)
{
FILE *fp1, *fp2;
char ch, buf[20], *pos;
int n;
pos = buf;
if ((fp1 = fopen(argv[1],"r")) == NULL)
{
puts("File cannot be opened");
exit(1);
}
fp2 = fopen(argv[2], "w");
while ((n = fread(pos, sizeof(char), 20, fp1)) == 20)
{
fwrite(pos, sizeof(char), 20, fp2);
}
fwrite(pos, sizeof(char), n, fp2);
fclose(fp1);
fclose(fp2);
exit(0);
}
Following is the program
#include <stdio.h>
#include<fcntl.h>
#include<errno.h>
void main(int argc,char **argv)
{
//FILE *fp1, *fp2; no longer needed
char ch, buf[20], *pos;
int n;
pos = buf;
//created file descripter for files
int fp1, fp2;
//fp1 = fopen(argv[1],"r") changed to
if ((fp1 = open(argv[1], O_RDONLY)) == -1)
{
puts("File cannot be opened");
exit(1);
}
//fp2 = fopen(argv[2], "w"); changed to
fp2 = open(argv[2], O_WRONLY);
//n = fread(pos, sizeof(char), 20, fp1) changed to
while ((n = read (fp1, pos, 20)) == 20)
{
//fwrite(pos, sizeof(char), 20, fp2); changed to
write (fp2, pos, 20);
}
//fwrite(pos, sizeof(char), n, fp2);changed to
write (fp2, pos, n);
//fclose(fp1); changed to
close(fp1);
//fclose(fp2); changed to
close(fp2);
exit(0);
}
------------------------------------------
In Short, new syntax is this and it is no longer required to enter Size of Byte parameter,
int open (const char* Path, int flags [, int mode ]);
int close(int fd);
size_t read (int fd, void* buf, size_t cnt);
size_t write (int fd, void* buf, size_t cnt);
as for detailed study of system calls regarding open write read and close you can use this reference:
https://www.geeksforgeeks.org/input-output-system-calls-c-create-open-close-read-write/