Intro to C #3: readline
No starter code for this assignment
Goals
- Yet more C practice
- Thinking in terms of functional interfaces rather than complete programs
- Using
malloc
andfree
Rubric
The problem with fgets
You used fgets
during the last assignment, but there was a big
problem: you could only read as many bytes (minus one, to account for the null-termination)
from the file as your buffer would hold. That's why I told you to assume that
no line would be longer than 200 bytes including the newline character.
But what if we could read a whole line, no matter how long? That would be
cool, right? We don't have infinite memory, of course, so there will still be
constraints on just how long our lines can be. But we ought to be able to create
something more convenient than fgets
. That's the goal of this
assignment.
Programming assignment #3: readline
For this assignment, you will write one C function, not a whole program. Here's its specification.
If you have a function like that, you can do things like this:
So far, so good. But I'm going to add more constraints on this function.
Here's how I want your readline
implementation to work.
IMPORTANT: put your implmentation of readline
alone in a file
named readline.c
. To test your function, use a separate file
called main.c
that looks like this:
Read the Makefile in readline-package.tar to see how main.c and readline.c get combined into a single program.
To compile your readline.c
and main.c
into a single
executable program, you do this:
That is, include both .c
files as command-line arguments for
the gcc
command.
IMPORTANT, PART 2: you may not call the standard library function
realloc
, but you might want to read about what it does.
Now wait a second...
If this readline
is so cool, why isn't it part of the standard library?
The big reason is that doing what I've described above is super-slow, and if you want to write slow code, you should probably just pick a language that does this automatic resizing for you, like Java or Python.
But doing this exercise in this class has two benefits.
- You learn about the "double + copy" algorithm for dynamically increasing the memory size of a data structure. This is a very important algorithm, and we'll discuss its big-O performance in class.
- You get to practice using
malloc
andfree
in a reasonably natural context.
Submitting your work
You know the drill by now. See the expected tar file name shown at the top of the page. You
may but need not include your main.c
. The grader will ignore it anyway.
Advice
Think carefully about when errors can occur naturally, and what to do when they do.
Have fun!
Keep experimenting! Keep asking questions!