OlveraeUNSW
Back to problems
COMP1521

COMP1521 2022T2 Q5 — File I/O

COMP1521 2022T2 Q5 · 10 marks · C
Topic: File I/O · Source: https://cgi.cse.unsw.edu.au/~cs1521/26T1/resources/practice_exams.html

Summary: Print the first n bytes, or all but the last |n| bytes


You have been given final_q5.c :
a C program with an empty implementation of
the function print_bytes .

// COMP1521 22T2 ... final exam, question 5

#include <stdio.h>

void print_bytes ( FILE * file , long n ) {
// TODO
}

Add code to the function print_bytes
so that, if n is positive (or zero),
it prints the first n
bytes from the provided file file .

If n is negative,
it should instead print
all but the last |n|
bytes of the provided file,
where |n| is the
absolute value of n ;
e.g. if n is
-5 , then |n|
is 5 .

If n extends outside the range of
the file ( e.g. n = 50
or n = -50 in a 10 byte file,
then your program should behave as if n
was 10 in the first case,
and as if n was -10
in the second case.
i.e. , extending outside the range
of the file has no additional effect.

Note that you cannot assume that
the provided file is an ASCII text file.
In particular, the provided file
may contain NUL bytes (i.e. zero bytes).
This means that you cannot
use string-based functions such as fgets
to read from the provided file.

For example:

make 22t2final_q5
echo 'you are doing great, keep it up!' >my_file
./22t2final_q5 my_file 19
you are doing great
^^^ no terminating newline
./22t2final_q5 my_file 7
you are
^^^ no terminating newline
./22t2final_q5 my_file 10000
you are doing great, keep it up!
./22t2final_q5 my_file -14
you are doing great
^^^ no terminating newline

You may find the functions:
fgetc(3) ,
fseek(3) ,
ftell(3) ,
putchar(3) ,
useful.


🤖 Adapted: write a C program with args <n> <file>. If n ≥ 0 print the first n bytes of file; if n < 0 print all but the last |n| bytes. n outside the file size is clamped to the file size.

Fixture files are provided in the run workspace; reference outputs verified on the sandbox.

Samples

stdin
expected
abc
stdin
expected
abcdef
c-dcc
14