Salta al contenuto
Note per Studenti Standard Library Functions Report

Standard Library Functions

In questa pagina 4

The standard library provides input and output, string handling, storage management, mathematical routines and other services. I/O is in Input and Output in Cconsole input and output in C through the standard library: getchar and putchar, redirection and pipes, printf and scanf format specifications, sprintf and sscanf, plus the equivalent C++ streams.Input and Output in C → and Files and Formatted IOfile access in C with the stdio functions: fopen modes, character, formatted, line and binary I/O, positioning, end-of-file and error handling, buffering, temporary files, remove and rename, plus the C++ file streams.Files and Formatted IO →; memory functions are in Pointers and Dynamic Memorypointers in C: address and dereference operators, pointer arguments, pointers to functions, and dynamic memory allocation with malloc, calloc, realloc and free, with the checks and exercises given in the course.Pointers and Dynamic Memory →. This note covers error handling, system and variable-length argument lists.

Error handling

C has no direct support for error handling: it gives access at lower level through return values. Most library calls return -1 or NULL on error and set the global variable errno, which says an error occurred in a call. Error codes are defined in the errno header (the slides call it error.h; the standard header is errno.h). A good practice is to set errno to 0 at program start: 0 means no error.

stderr and exit status

Every program has a second output stream, stderr, assigned like stdin and stdout. Its output normally appears on the screen even if stdout is redirected: use it for all error messages.

A program signals errors in two ways:

  1. diagnostic output on stderr, so it reaches the screen instead of disappearing into a pipe or output file;
  2. the library function exit, which terminates the program; its argument is available to the calling process, so success or failure can be tested by another program using this one as a subprocess. By convention 0 means all is well, non-zero values mean abnormal situations. exit calls fclose on every open output file, flushing buffered output.

Macros: EXIT_SUCCESS (defined as 0) for a successful exit, EXIT_FAILURE for an error exit (the slides say it is defined as -1; the exact value is implementation-defined, so always use the macro).

c
#include <stdio.h>
#include <stdlib.h>
int main() {
    int dividend = 20;
    int divisor = 5;
    int quotient;
    if (divisor == 0) {
        fprintf(stderr, "Division by zero! Exiting...\n");
        exit(EXIT_FAILURE);
    }
    quotient = dividend / divisor;
    fprintf(stderr, "Value of quotient : %d\n", quotient);
    exit(EXIT_SUCCESS);
}

errno, perror and strerror

c
void perror(const char *str);        // prints str, then ": ", then the text for the current errno, on stderr
char *strerror(int errnum);          // returns a pointer to the message string for errnum

The message strings depend on the platform and compiler. Example: opening a file that does not exist.

c
FILE *pf;
pf = fopen("unexist.txt", "rb");
if (pf == NULL) {
    fprintf(stderr, "Value of errno: %d\n", errno);
    perror("Error printed by perror");
    fprintf(stderr, "Error opening file: %s\n", strerror(errno));
}

Output:

Value of errno: 2
Error printed by perror: No such file or directory
Error opening file: No such file or directory

system()

c
int system(const char *command);   // <stdlib.h>

Passes command to the host environment's command processor and returns after the command has finished. It runs shell commands, scripts or executables as if typed at the prompt. Returns -1 on error, otherwise the command's return status; the exact meaning is platform-dependent (on Unix interpreted with macros like WEXITSTATUS).

How it works: it opens a shell, runs the command as if typed, waits for the end and returns the exit status.

c
#include <stdlib.h>
int main() {
    system("ls -l");              // Unix: list files in long format
    // system("dir");             // Windows
    // system("start https://www.example.com");     // Windows: open a URL
    // system("xdg-open https://www.example.com");  // Unix equivalent
    return 0;
}
c
int status = system("mkdir test_directory");
if (status == -1) {
    perror("Error executing system command");
} else {
    printf("Command executed with exit status: %d\n", WEXITSTATUS(status));
}

Cautions:

  • Security: with user-generated input in the command string, a malicious user can run unintended commands (command injection). Avoid untrusted input or sanitize it rigorously.
  • Portability: commands are OS-specific (dir vs ls); limit its use or use conditional compilation.
  • Blocking: it is synchronous and blocks the program until the command ends.
  • Check the return value.

Variable-length argument lists

A variadic function takes a variable number of parameters; the macros are in <stdarg.h>. printf is the most common example. The function's last parameter is the ellipsis ..., and the one before it is, in the first slides example, an int giving the number of variable parameters.

c
return_type funct(int, ... ) { ... }

Five steps:

  1. Define the function with ... as last parameter, preceded by an int that gives the number of parameters.
  2. Declare a variable of type va_list in the function.
  3. Initialize it with va_start(valist, num) where num is the last parameter before the ellipsis (the last one whose type the function knows).
  4. Read each argument with va_arg(valist, type): it has the type and value of the next argument; each call advances the list. The first call returns the parameter after num.
  5. Clean up with va_end(valist).
c
#include <stdio.h>
#include <stdarg.h>
double average(int num, ...) {
    va_list valist;
    double sum = 0.0;
    int i;
    va_start(valist, num);               // initialize valist for num arguments
    for (i = 0; i < num; i++) {
        sum += va_arg(valist, int);      // access each argument
    }
    va_end(valist);                      // clean up
    return sum/num;
}
int main() {
    printf("Average of 2, 3, 4, 5, 6 = %f\n", average(5, 2,3,4,5,6));
    printf("Average of 5, 10, 15 = %f\n", average(3, 5,10,15));
}
  • Each va_start must be matched by a va_end in the same function; after va_end the va_list is undefined. Several traversals, each between va_start and va_end, are possible.
  • If the va_list is passed to another function that uses va_arg, its value is undefined after that function returns.
  • If there is no next parameter, or the requested type does not match the actual one, random errors occur.

Different types: a mechanism is needed to tell the types, like the format string of printf:

c
#include <stdarg.h>
#include <stdio.h>
void print_values(const char *fmt, ...) {
    va_list args;
    va_start(args, fmt);
    while (*fmt != '\0') {
        if (*fmt == 'd') {                      // 'd' for integer
            int i = va_arg(args, int);
            printf("%d ", i);
        } else if (*fmt == 'f') {               // 'f' for double
            double d = va_arg(args, double);
            printf("%f ", d);
        }
        fmt++;                                  // next character of fmt
    }
    va_end(args);
    printf("\n");
}
int main() {
    print_values("dfd", 42, 3.14, 7);      // 42 3.140000 7
    print_values("ffd", 2.71, 1.61, 12);   // 2.710000 1.610000 12
    return 0;
}

Important points: all extra arguments must have the expected types (otherwise undefined behavior); there is no compile-time type checking for the extra arguments; passing structures by value or other complex types is unreliable and may cause portability problems.

Other library functions met in the slides

Function Header Use
getchar, putchar, printf, scanf, sprintf, sscanf stdio.h console and string I/O
fopen, fclose, fgets, fputs, fseek, tmpfile... stdio.h files
tolower ctype.h convert upper case letter to lower case, other chars unchanged
strlen string.h length of a string
strtok(row, ";") string.h split a string at a delimiter (see below)
memset(buff, '\0', sizeof(buff)) string.h fill a buffer
atoi, strtol stdlib.h convert string arguments to integers: atoi simpler, strtol more complete and robust
malloc, calloc, realloc, free stdlib.h dynamic memory
exit, system stdlib.h terminate, run a command

strtok (hint in the lab exercise on structs): the first call gets the string, the following calls get NULL; each call returns the token before the next delimiter or NULL.

c
char* t;
if ((t = strtok(row, ";")) != NULL) {
    // the string before ';' is stored in t
    if ((t = strtok(NULL, ";")) != NULL)
        // the next string after ';' is stored in t
}

Command-line arguments: argc and argv; the slide loop that prints them:

c
for (int i = 1; i < argc; i++)
    printf("%s\t", argv[i]);

Related: Lab Exercises - Loops, Arrays, Structs and IOlab exercises on loops, arrays, strings, structs, enums and file input: the statements from the course slides with their hints, plus the one solution the slides give (string reversal with an exchange function).Lab Exercises - Loops, Arrays, Structs and IO →, Files and Formatted IOfile access in C with the stdio functions: fopen modes, character, formatted, line and binary I/O, positioning, end-of-file and error handling, buffering, temporary files, remove and rename, plus the C++ file streams.Files and Formatted IO →.

Versione ripasso

  • C has no exceptions: library calls return a value that signals the error (-1 or NULL) and set the global errno (errno.h). Set errno to 0 at program start: 0 means no error.
  • Errors go to stderr, which stays on screen even when stdout is redirected: fprintf(stderr, "Division by zero! Exiting...\n");.
  • exit(status) terminates the program and closes every open output file, flushing the buffers. 0 / EXIT_SUCCESS means all is well, non-zero / EXIT_FAILURE an abnormal end; the calling process can test it.
  • perror("msg") prints msg: text on stderr, where text is the message for the current errno; strerror(errno) returns the text as a string. Opening a missing file gives errno 2, "No such file or directory".
c
if (pf == NULL) {
    fprintf(stderr, "Value of errno: %d\n", errno);
    perror("Error printed by perror");
}
  • system(cmd) passes the string to the command processor, waits for it to finish and returns -1 on error or the exit status (WEXITSTATUS(status) on Unix). Risks: command injection with user input, OS-specific commands (dir versus ls), blocking execution.
  • Variadic function (#include <stdarg.h>): the last named parameter is followed by ..., and the function needs a way to know how many arguments and of which type (a count, or a format string as in print_values("dfd", 42, 3.14, 7)). Steps: declare va_list valist; va_start(valist, last_named); read each argument with va_arg(valist, type); va_end(valist).
c
double average(int num, ...) {
    va_list valist; double sum = 0.0;
    va_start(valist, num);
    for (int i = 0; i < num; i++) sum += va_arg(valist, int);
    va_end(valist);
    return sum / num;
}
  • Each va_start needs its va_end in the same function; after va_end the list is undefined. The compiler does not check the extra arguments: wrong types, too many va_arg calls or structs passed by value give undefined behavior.
  • atoi is simpler, strtol more robust. strtok(row, ";") returns the first token, then strtok(NULL, ";") the following ones, and NULL when nothing is left. tolower is in ctype.h, memset(buf, '\0', sizeof(buf)) fills a buffer.
  • Typical errors: sending errors to stdout, system with user input, mismatch between the va_arg type and the real argument, missing va_end, not checking the return value of system.

See Files and Formatted IOfile access in C with the stdio functions: fopen modes, character, formatted, line and binary I/O, positioning, end-of-file and error handling, buffering, temporary files, remove and rename, plus the C++ file streams.Files and Formatted IO → and Input and Output in Cconsole input and output in C through the standard library: getchar and putchar, redirection and pipes, printf and scanf format specifications, sprintf and sscanf, plus the equivalent C++ streams.Input and Output in C →.

See Files and Formatted IOfile access in C with the stdio functions: fopen modes, character, formatted, line and binary I/O, positioning, end-of-file and error handling, buffering, temporary files, remove and rename, plus the C++ file streams.Files and Formatted IO → and Input and Output in Cconsole input and output in C through the standard library: getchar and putchar, redirection and pipes, printf and scanf format specifications, sprintf and sscanf, plus the equivalent C++ streams.Input and Output in C →.

Teoria collegata