Write a small C program newcat , which performs exactly as oldcat (shown below)
ID: 3793149 • Letter: W
Question
Write a small C program newcat, which performs exactly as oldcat (shown below), but uses UNIX system calls for input/output. Specifically, use the UNIX system calls whose prototypes are shown below:
int read(int fd, char *buf, int n); ........... int write(int fd, char *buf, int n);
int open(char *name, int accessmode, int permission); ........... int close(int fd);
To open a file for read, you can use the symbolic constant O_RDONLY defined in fcntl.h header file to specify the accessmode. Simply pass 0 for permission. That is, the code will appear as follows:
fd = open (filename, O_RDONLY, 0);
You will need the following header files: sys/types.h, unistd.h and fcntl.h
Compile and test the program. Produce a script file containing the source code and several executions. Please be sure to include test situations where a file to be concatenated could not be opened, and where no command line argument is provided.
#include <stdio.h>
#include <stdlib.h>
/* oldcat: Concatenate files */
int main(int argc, char *argv[])
{
void filecopy(FILE *, FILE *); /* prototype for function */
FILE *fp;
char *prog = argv[0]; /* program name for errors */
if (argc == 1) /* no args; copy standard input */
filecopy(stdin, stdout);
else
while (--argc > 0)
if ((fp = fopen(*++argv, "r")) == NULL) {
fprintf(stderr, "%s: can't open %s ", prog, *argv);
exit(-1);
} else {
filecopy(fp, stdout);
fclose(fp);
}
exit(0);
}
/* filecopy: copy file ifp to ofp */
void filecopy(FILE *ifp, FILE *ofp)
{
int c;
while ((c = getc(ifp)) != EOF)
putc(c, ofp);
}
Explanation / Answer
The code is
#include <sys/types.h>
#include <unistd.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#define BUFFER 4096
/* newcat: Concatenate files */
int main(int argc, char *argv[])
{
void filecopy(int, int); /* prototype for function */
int fd;
char *prog = argv[0]; /* program name for errors */
if (argc == 1) /* no args; copy standard input */
filecopy(STDIN_FILENO, STDOUT_FILENO);
else
while (--argc > 0) {
fd = open(*++argv, O_RDONLY);
if (fd == -1) {
perror ("open");
exit(-1);
} else {
filecopy(fd, STDOUT_FILENO);
close(fd);
}
}
exit(0);
}
/* filecopy: copy input fd data to output fd*/
void filecopy(int inputfd, int outputfd)
{
int c;
ssize_t bytes_read, bytes_write;
char buffer[BUFFER];
while((bytes_read = read (inputfd, &buffer, BUFFER)) > 0){
bytes_write = write (outputfd, &buffer, (ssize_t) bytes_read);
if(bytes_write != bytes_read){
perror("Unable to write the data");
return;
}
}
}
Assume a file a.txt which contains text Hello
Run gcc a.c
./a.out a.txt
Hello
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.