|
CS456 - Systems Programming
Spring 2026
|
Displaying ./code/h2/concat.c
/*
we start with a simple version of the cat command, and will make some
a few improvements.
i've included below a header file i made myself called "extras.h" that currently
has two functions:
get_fdSize - takes a file descriptor, returns the size of the file
int get_fdSize(int fd);
get_fdPerms - takes a file descriptor, returns the file permissions
int get_fdPerms(int fd);
For this program, you will only need one of these (figure out which one!)
You will make the following improvements:
1. Currently, this is hardcoded to read up to 1024 bytes, change this so that it
will read and write whatever the size of the file is
2. If more than 1 file is provided on the command line, print that file too
Ex:
> ./concat hello
Will print the contents of the file "hello" to standard output
> ./concat hello world
Will print the contents of the file "hello" and the contents of the file
"world" to standard output
If there is an error opening that file, just print an error message and skip
printing it.
Compile
> gcc -o concat concat.c
*/
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
//including my own header file here
#include "extras.h"
int main(int argc, char **argv){
//prints usage statement if required arguments are unavailable
if(argc < 2){
fprintf(stderr, "Usage: %s files ...\n", argv[0]);
exit(1);
}
//declares file descriptor and opens source file for reading
int src = open(argv[1], O_RDONLY);
//check return value for errors
if(src == -1){
fprintf(stderr, "Error in %s: ", argv[1]);
perror("open");
exit(-1);
}
//creating arrays for buffer
char buffer[1024];
int data = read(src, buffer, 1024);
write(1, buffer, data);
close(src);
return 0;
}
|