C Stdlib Notes

From Rebertia

Jump to: navigation, search

Contents

stdlib.h

All but free() return NULL on error.

  • void* malloc(sizeInBytes)
  • void* calloc(lengthOfArray, sizeOfArrayElement) - zeros memory beforehand
  • void* realloc(void*, newSizeInBytes)
  • void free(void*)

stdio.h

Basics

  • FILE* fopen(filename, mode) - NULL on error
  • FILE* freopen(filename, mode, FILE*) - used to redirect stdin, stdout, etc. NULL & closes file on error
  • int fclose(FILE*) - EOF on error
  • int fflush(FILE*) - EOF on error
  • FOPEN_MAX - max # of files you can have open
  • FILENAME_MAX - length of longest possible filename
  • EOF - End Of File sentinel value
  • int fputs(char[], FILE*) - EOF on error
  • char[] fgets(char[] buffer, bufferSize, FILE*) - stops on newline (but will include it). returns NULL on error/EOF, otherwise returns buffer itself
  • int fprintf(FILE*, format, ...) - # chars printed, or EOF on error
  • int fscanf(FILE*, format, ...) - EOF on immediate error, # values assigned otherwise (< expected indicates error)

Low-level

  • int getc(FILE*) - EOF on error
  • int ungetc(char, FILE*) - EOF on error
  • int putc(char, FILE*) - EOF on error

Misc

  • int snprintf(char[] buffer, sizeOfBuffer, format, ...)
  • int sscanf(char[] source, format, ...)
  • bool ferror(FILE*) - check FILE's error flag
  • bool feof(FILE*) - is position @ EOF?
  • void clearerr(FILE*) - clears error+EOF flags

Random access

  • long ftell(FILE*) - returns file position. on error, returns -1 and sets errno
  • int fseek(FILE*, long offsetInBytes, origin) - returns -1 on error
    • origin values:
      • SEEK_SET - start of file
      • SEEK_CUR - current position
      • SEEK_END - EOF

NOTE: some things not actually ints in the preceding

Binary streams only

  • int fread(void* object, sizeOfObject, numberOfObjects, FILE*) - reads object in from file. returns # of objs read; if < numberOfObjects, then error/EOF
  • int fwrite(void* object, sizeOfObject, numberOfObjects, FILE*) - reads object in from file. returns # of objs written; if < numberOfObjects, then error/EOF

string.h

  • char[] strerror(errno) - error message describing error
Personal tools