Commit 46a60dce authored by kjc015's avatar kjc015
Browse files

Exercise 3 Done

parent cd8a8a7f
CFLAGS=-Wall -Werror
head2: head2.o fileio.o
$(CC) $(CFLAGS) head2.o fileio.o -o head2
%.o: %.c
#include "fileio.h"
int read_file_bytes (char* filename, int bytes, char* buffer)
* Reads byte data from a file and appends a null terminator (byte value of zero, 0).
* filename: full path and filename to read from.
* bytes: maximum number of bytes to read.
* buffer: where to put the read data (note need bytes+1!).
* Return value: number of bytes read or -1 on error.
int opn;
int rd;
opn = open(filename, O_RDONLY);
rd = read(opn, buffer, bytes);
buffer[bytes] = '\0';
return rd;
#ifndef __fileio_h_
#define __fileio_h_
// for O_RDONLY, etc.
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAXBYTES 1024
int read_file_bytes (char* filename, int bytes, char* buffer);
/* Kyle Chrysler
* Tuesday 1:20
* lab 04 - head.c
* compile with: head
* notes: none
// for O_RDONLY, etc.
#include "fileio.h"
#define MAXBYTES 1024
int main(int argc, char* argv[])
int readbytes = 10; // default to 10 bytes
char buffer[MAXBYTES+1]; // buffer to hold file data
if (argc < 2){
// missing required argument
printf("Usage %s <filename> [<bytes>]\n",
if (argc > 2){
// process optional bytes argument
readbytes = atoi(argv[2]);
if (readbytes > MAXBYTES){
printf("bytes is too large, max supported value is %d!\n",
if (read_file_bytes(argv[1], readbytes, buffer) >= 0){
printf("%s\n", buffer);
} else {
printf("Error: could not read file!\n");
return 0;
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment