Tip:
Highlight text to annotate it
X
Here's my read all function--this is the code I just took a few minutes to write,
and what you can see is that I've included a couple of assertions.
The first thing that I've asserted that the file descriptor passed 10 is greater than or equal to 0.
These file descriptors are integers usually small ones and they have to be non-negative.
The second thing we're going to assert is that buf that is to say pointing to the block of memory
into which we're going to read data can't be the null pointer and just asserting buf like this
is implicitly a test that the pointers not null in C.
And the third thing we're going to assert is that the number of bytes to read is also non-negative.
So, given that setup and we're just going little sanity checking here, we can get to the main logic.
So the first thing we're going to do is initialize a left variable which is going to be the number of bytes
left to read to initially be the total number of bytes to read.
Now we're going to enter our while loop--the while loop is going to operate until either
the read system call returns something less than 1 that is to say it returns 0
indicating an end of file condition or -1 indicating an error.
And if either of those things happens, we're just going to return that value to our caller.
If read work that is to say it read some positive number of bytes, we're going to increment
the buffer pointer by that number of bytes, reduce the amount of bytes left by that number of bytes,
assert the number of bytes left hasn't gone negative due to some sort of a logic error,
and now finally if there are no bytes left, we're going to return the number of bytes read
which has to be just the original number of bytes but these asked to read.
So this is pretty simple code and I would expect or at least I would hope to be able to get it right
but I know from vast prior experience that I never get this stuffed right the first time,
so what I want to do is be able to test it.
So what I've done is written a little test runners, and so what the test runners does is opens a program
and so here we're just using a splay tree from Python that happens to be in this directory
and allocating a buffer and we don't need to worry about the details here
and then what we're going to do is 100 different times we're going to issue the read all command
to read the contents of the file into the buffer and then we're going to assert that
read all--always read the full number of bytes we're trying to read and then
we're also going to assert using a memory comparison function that
the contents of that file are the contents that we expected.
Its definitive variables initializes some code I didn't really talked about
to contain the data from the file.
And so what you're going to say if we do this 100 times, then our new read all call passes.
And so let's look at what happens.