Write a small C program newcat which performs exactly as old
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. Thanks a lot for your help!!!
#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);
}
Solution
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <string.h>
/* oldcat: Concatenate files */
int main(int argc, char *argv[])
{
void filecopy(int, int); /* prototype for function */
int fd; //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((fd=open(*++argv, O_RDONLY))== -1){// if ((fp = fopen(*++argv, \"r\")) == NULL) {
fprintf(stderr, \"%s: can\'t open %s\ \", prog, *argv);
exit(-1);
} else {
filecopy(fd, stdout);
close(fd);//fclose(fp);
}
exit(0);
}
/* filecopy: copy file ifp to ofp */
//void filecopy(FILE *ifp, FILE *ofp)
void filecopy(int ifp, int ofp)
{
int c;
char a[256];
read(ifp, a, 256);//while ((c = getc(ifp)) != EOF)
write(ofp, a, strlen(a)); //putc(c, ofp);
}


