|
CS456 - Systems Programming
Spring 2025
|
Displaying ./code/Jan30/myCat_sys.c
/*
implementing a version of the "cat" command using Linux System Calls
*/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/stat.h>
int main(int argc, char **argv){
if(argc < 2){ //prints usage statement to stderr if not enough arguments
//file descriptor 2 is stderr
write(2,"Usage: mycat filename\n", 22);
return 1;
}
//declares file descriptor, tries to open file specified by user
int fd;
fd = open(argv[1], O_RDONLY);
//if file does not exist, print usage statement to stderr and exit the program
if(fd == -1){
write(2,"open failed\n", 12);
return -1;
}
//if we get here, we've sucessfully opened the program
//getting the size of the file
int size;
struct stat st; //needed so we can use stat
fstat(fd, &st); //accessing the stat struct
size = st.st_size; //getting file size
//printf("%d\n", size); //for debugging purposes only
char buf[size+1]; //setting up the buffer to read into
read(fd, buf, size); //reading the file contents into a buffer
//read returns the number of bytes read
write(1, buf, size); //writing the file contents to stdout
// file descriptor 1 is stdout
//we are done now, so close the file descriptor
close(fd);
return 0;
}
|