AspiringCodeMonkey AspiringCodeMonkey - 1 month ago 4
C Question

How should a C library alert the user to bad input, and other intro library concerns

I am writing a small, C shared library, with a fairly basic set of tasks.

The reason I am writing it is that it's part of an interview process. It is expected that people attempting this exercise are junior/intro developers.

I am fairly new to C and have completed the exercise handily, in the specified environment, but I have never built a library before. Since my methods will be called from inside another program, how should I deal with faulty user input?

I am allowed to ask questions and asked one about dealing with this facet explicitly, but received the reply that it is up to the candidate to choose how to deal with errors.

I have read some things about using errno, some good, some bad. Is it standard to report errors using this macro?

I am starting to think about things like portability, but part of the assignment is to use a certain version of Linux and to use the gcc compiler. I think as long as I make a reasonable attempt to make my solution portable, I will be fine.

Are there other things a newb trying to write a library should think about?


errno is the most useful method in the standard library for error reporting. string.h also defines a helpful function called strerror that will transform the error code to a string. Here's a sample function you can use to report errors.

#include <errno.h>
#include <string.h>

void error_quit(char *message)
    int errcode = errno;
    fprintf(stderror,"Error at %s: %s\n",message,strerror(errcode));

Call this setting message to whatever error reporting message you want. For example, if you want to check if read fails (helpful for checking user input):

int n = read(fd,buf,sizeof(buf));
if (n <= 0)

It will give the user descriptive information about why read failed. Any problems with the user input will be displayed.