\section{Common C Functions}

To find more information about any functions, please use the man pages.
Note the man pages are organized into sections.
Section 2 are System calls.
Section 3 are C libraries.
On the web, Google \keyword{man 7 open}.
In the shell, \keyword{man -S2 open} or \keyword{man -S3 printf}

\subsection{Handling Errors}

Before we get into the nitty gritty of all the functions, know that most functions in C handle errors return oriented.
This is at odds with programming languages like C++ or Java where the errors are handled with exceptions.
There are a number of arguments against exceptions.

\begin{enumerate}
\item Exceptions make control flow harder to understand.
\item Exception oriented languages need to keep stack traces and maintain jump tables.
\item Exceptions may be complex objects.
\end{enumerate}

There are a few arguments for exceptions as well

\begin{enumerate}
\item Exceptions can come from several layers deep.
\item Exceptions help reduce global state.
\item Exceptions differentiate business logic and normal flow.
\end{enumerate}

Whatever the pros/cons are, we use the former because of backwards compatibility with languages like FORTRAN \cite[P. 84]{fortran72}.
Each thread will get a copy of \keyword{errno} because it is stored at the top of each thread's stack -- more on threads later.
One makes a call to a function that could return an error and if that function returns an error according to the man pages, it is up to the programmer to check errno.

\begin{lstlisting}[language=C]
#include <errno.h>

FILE *f = fopen("/does/not/exist.txt", "r");
if (NULL == f) {
    fprintf(stderr, "Errno is %d\n", errno);
    fprintf(stderr, "Description is %s\n", strerror(errno));
}
\end{lstlisting}

There is a shortcut function \keyword{perror} that prints the english description of errno.
Also, a function may return the error code in the return value itself.

\begin{lstlisting}[language=C]
int s = getnameinfo(...);
if (0 != s) {
     fprintf(stderr, "getnameinfo: %s\n", gai_strerror(s));
}
\end{lstlisting}

Be sure to check the man page for return code characteristics.

\subsection{Input / Output}

In this section we will cover all the basic input and output functions in the standard library with references to system calls.
Every process has three streams of data when it starts execution: standard input (for program input), standard output (for program output), and standard error (for error and debug messages).
Usually, standard input is sourced from the terminal in which the program is being run in, and standard out is the same terminal.
However, a programmer can use redirection such that their program can send output and/or receive input, to and from a file, or other programs.

They are designated by the file descriptors 0 and 1 respectively. 2 is reserved for standard error which by library convention is unbuffered (i.e. IO operations are performed immediately).

\subsubsection{stdout oriented streams}

Standard output or stdout oriented streams are streams whose only options are to write to stdout.
\keyword{printf} is the function with which most people are familiar in this category.
The first parameter is a format string that includes placeholders for the data to be printed.
Common format specifiers are the following
\begin{enumerate}
\item \keyword{\%s} treat the argument as a c string pointer, keep printing all characters until the NULL-character is reached
\item \keyword{\%d} prints the argument as an integer
  \item \keyword{\%p} print the argument as a memory address.
    \end{enumerate}
For performance, \keyword{printf} buffers data until its cache is full or a newline is printed.
Here is an example of printing things out.

\begin{lstlisting}[language=C]
char *name = ... ; int score = ...;
printf("Hello %s, your result is %d\n", name, score);
printf("Debug: The string and int are stored at: %p and %p\n", name, &score );
// name already is a char pointer and points to the start of the array.
// We need "&" to get the address of the int variable
\end{lstlisting}

From the previous section,
\keyword{printf} calls the system call \keyword{write}.
\keyword{printf} is a C library function, while \keyword{write} is a system call system.

The buffering semantics of printf is a little complicated.
ISO defines three types of streams \cite[P. 278]{ISON1124}
\begin{itemize}
\item Unbuffered, where the contents of the stream reach their destination as soon as possible.
\item Line Buffered, where the contents of the stream reach their destination as soon as a newline is provided.
\item Fully Buffered, where the contents of the stream reach their destination as soon as the buffer is full.
\end{itemize}

Standard Error is defined as ``not fully buffered'' \cite[P. 279]{ISON1124}.
Standard Output and Input are merely defined to be fully buffered if and only if the stream destination is not an interactive device.
Usually, standard error will be unbuffered, standard input and output will be line buffered if the output is a terminal otherwise fully buffered.
This relates to printf because printf merely uses the abstraction provided by the FILE interface and uses the above semantics to determine when to write.
One can force a write by calling fflush() on the stream.

To print strings and single characters, use \keyword{puts(char\ *name\ )} and \keyword{putchar(char\ c\ )}

\begin{lstlisting}[language=C]
puts("Current selection: ");
putchar('1');
\end{lstlisting}

\subsubsection{Other streams}

To print to other file streams, use \keyword{fprintf(\ \_file\_\ ,\ "Hello\ \%s,\ score:\ \%d",\ name,\ score);} Where \_file\_ is either predefined (`stdout' or `stderr') or a FILE pointer that was returned by \keyword{fopen} or \keyword{fdopen}.
There is a printf equivalent that works with file descriptors, called dprintf.
Just use \keyword{dprintf(int\ fd,\ char*\ format\_string,\ ...);}.

To print data into a C string, use \keyword{sprintf} or better \keyword{snprintf}.
\keyword{snprintf} returns the number of characters written excluding the terminating byte.
We would use \keyword{sprintf} the size of the printed string is less than the provided buffer -- think about printing an integer, it will never be more than 11 characters with the NUL byte.
If printf is dealing with variadic input, it is safer to use the former function as shown in the following snippet.

\begin{lstlisting}[language=C]
// Fixed
char int_string[20];
sprintf(int_string, "%d", integer);

// Variable length
char result[200];
int len = snprintf(result, sizeof(result), "%s:%d", name, score);
\end{lstlisting}

\subsection{stdin oriented functions}

Standard input or stdin oriented functions read from stdin directly.
Most of these functions have been deprecated due to them being poorly designed. These functions treat stdin as a file from which we can read bytes.
One of the most notorious offenders is \keyword{gets}.
\keyword{gets} is deprecated in C99 standard and has been removed from the latest C standard (C11).
The reason that it was deprecated was that there is no way to control the length being read, therefore buffers could get overrun easily.
When this is done maliciously to hijack program control flow, this is known as a buffer overflow.

Programs should use \keyword{fgets} or \keyword{getline} instead.
Here is a quick example of reading at most 10 characters from standard input.

\begin{lstlisting}[language=C]
char *fgets (char *str, int num, FILE *stream);

ssize_t getline(char **lineptr, size_t *n, FILE *stream);

// Example, the following will not read more than 9 chars
char buffer[10];
char *result = fgets(buffer, sizeof(buffer), stdin);
\end{lstlisting}

Note that, unlike \keyword{gets}, \keyword{fgets} copies the newline into the buffer.
On the other hand, one of the advantages of \keyword{getline} is that will automatically allocate and reallocate a buffer on the heap of sufficient size.

\begin{lstlisting}[language=C]
// ssize_t getline(char **lineptr, size_t *n, FILE *stream);

/* set buffer and size to 0; they will be changed by getline */
char *buffer = NULL;
size_t size = 0;

ssize_t chars = getline(&buffer, &size, stdin);

// Discard newline character if it is present,
if (chars > 0 && buffer[chars-1] == '\n')
buffer[chars-1] = '\0';

// Read another line.
// The existing buffer will be re-used, or, if necessary,
// It will be `free`'d and a new larger buffer will `malloc`'d
chars = getline(&buffer, &size, stdin);

// Later... don't forget to free the buffer!
free(buffer);
\end{lstlisting}

In addition to those functions, we have \keyword{perror} that has a two-fold meaning.
Let's say that a function call failed using the errno convention.
\keyword{perror(const\ char*\ message)} will print the English version of the error to stderr.

\begin{lstlisting}[language=C]
int main(){
  int ret = open("IDoNotExist.txt", O_RDONLY);
  if(ret < 0){
    perror("Opening IDoNotExist:");
  }
  //...
  return 0;
}
\end{lstlisting}

To have a library function parse input in addition to reading it, use \keyword{scanf} (or \keyword{fscanf} or \keyword{sscanf}) to get input from the default input stream, an arbitrary file stream or a C string, respectively.
All of those functions will return how many items were parsed.
It is a good idea to check if the number is equal to the amount expected.
Also naturally like \keyword{printf}, \keyword{scanf} functions require valid pointers.
Instead of pointing to valid memory, they need to also be writable.
It's a common source of error to pass in an incorrect pointer value.
For example,

\begin{lstlisting}[language=C]
int *data = malloc(sizeof(int));
char *line = "v 10";
char type;
// Good practice: Check scanf parsed the line and read two values:
int ok = 2 == sscanf(line, "%c %d", &type, &data); // pointer error
\end{lstlisting}

We wanted to write the character value into c and the integer value into the malloc'd memory.
However, we passed the address of the data pointer, not what the pointer is pointing to!
So \keyword{sscanf} will change the pointer itself.
The pointer will now point to address 10 so this code will later fail when free(data) is called.

Now, scanf will keep reading characters until the string ends.
To stop scanf from causing a buffer overflow, use a format specifier.
Make sure to pass one less than the size of the buffer.

\begin{lstlisting}[language=C]
char buffer[10];
scanf("%9s", buffer); // reads up to 9 characters from input (leave room for the 10th byte to be the terminating byte)
\end{lstlisting}

One last thing to note is if system calls are expensive, the \keyword{scanf} family is much more expensive due to compatibility reasons.
Since it needs to be able to process all of the printf specifiers correctly, the code isn't efficient \todo{citation needed}.
For highly performant programs, one should write the parsing themselves.
If it is a one-off program or script, feel free to use scanf.

\subsection{string.h}

String.h functions are a series of functions that deal with how to manipulate and check pieces of memory.
Most of them deal with C-strings.
A C-string is a series of bytes delimited by a NUL character which is equal to the byte 0x00.
\href{https://linux.die.net/man/3/string}{More information about all of these functions}.
Any behavior missing from the documentation, such as the result of \keyword{strlen(NULL)} is considered undefined behavior.

\begin{itemize}

	\item \keyword{int strlen(const char *s)} returns the length of the string.

	\item \keyword{int strcmp(const char *s1, const char *s2)} returns an integer determining the lexicographic order of the strings.
    If s1 where to come before s2 in a dictionary, then a -1 is returned.
    If the two strings are equal, then 0.
    Else, 1.

	\item \keyword{char *strcpy(char *dest, const char *src)} Copies the string at \keyword{src} to \keyword{dest}.
    \textbf{This function assumes dest has enough space for src otherwise undefined behavior}

	\item \keyword{char *strcat(char *dest, const char *src)} Concatenates the string at \keyword{src} to the end of destination.
    \textbf{This function assumes that there is enough space for \keyword{src} at the end of destination including the NUL byte}

	\item \keyword{char *strdup(const char *dest)} Returns a \keyword{malloc}'d copy of the string.

	\item \keyword{char *strchr(const char *haystack, int needle)} Returns a pointer to the first occurrence of \keyword{needle} in the \keyword{haystack}.
    If none found, \keyword{NULL} is returned.

	\item \keyword{char *strstr(const char *haystack, const char *needle)} Same as above but this time a string!

	\item \keyword{char *strtok(const char *str, const char *delims)}

	  A dangerous but useful function strtok takes a string and tokenizes it.
    Meaning that it will transform the strings into separate strings.
    This function has a lot of specs so please read the man pages a contrived example is below.

	      \begin{lstlisting}[language=C]
        #include <stdio.h>
        #include <string.h>

        int main(){
          char* upped = strdup("strtok,is,tricky,!!");
          char* start = strtok(upped, ",");
          do{
            printf("%s\n", start);
          }while((start = strtok(NULL, ",")));
          return 0;
        }
\end{lstlisting}

	      \textbf{Output}

	      \begin{lstlisting}[language=console]
strtok
is
tricky
!!
\end{lstlisting}

	      Why is it tricky? Well what happens when upped is changed to the following?

	      \begin{lstlisting}[language=C]
        char* upped = strdup("strtok,is,tricky,,,!!");
\end{lstlisting}

	\item For integer parsing use
	      \keyword{long int strtol(const char *nptr, char **endptr, int base);}
	      or
	      \keyword{long long int strtoll(const char *nptr, char **endptr, int base);}.

	      What these functions do is take the pointer to your string
	      \keyword{*nptr} and a \keyword{base} (i.e. binary, octal, decimal,
	      hexadecimal etc) and an optional pointer \keyword{endptr} and returns a
	      parsed value.

	      \begin{lstlisting}[language=C]
        int main(){
          const char *nptr = "1A2436";
          char* endptr;
          long int result = strtol(nptr, &endptr, 16);
          return 0;
        }
\end{lstlisting}

	      Be careful though!
        Error handling is tricky because the function won't return an error code.
        If passed an invalid number string, it will return 0.
        The caller has to be careful from a valid 0 and an error.
        This often involves an errno trampoline as shown below.

	      \begin{lstlisting}[language=C]
        int main(){
          const char *input = "0"; // or "!##@" or ""
          char* endptr;
          int saved_errno = errno;
          errno = 0
          long int parsed = strtol(input, &endptr, 10);
          if(parsed == 0 && errno != 0){
            // Definitely an error
          }
          errno = saved_errno;
          return 0;
        }
\end{lstlisting}

	    \item \keyword{void *memcpy(void *dest, const void *src, size\_t n)} moves \keyword{n} bytes starting at \keyword{src} to \keyword{dest}.
        \textbf{Be careful}, there is undefined behavior when the memory regions overlap.
        This is one of the classic "This works on my machine!" examples because many times Valgrind won't be able to pick it up because it will look like it works on your machine.
        Consider the safer version \keyword{memmove}.

	    \item \keyword{void *memmove(void *dest, const void *src, size\_t n)} does the same thing as above, but if the memory regions overlap then it is guaranteed that all the bytes will get copied over correctly.
        \keyword{memcpy} and \keyword{memmove} both in \keyword{string.h}?
\end{itemize}


