The C Standard Library

Header files

Dynamic memory allocation

Both the following functions are contained in stdlib.h.

Common errors

Every block of memory allocated with malloc() should eventually be returned to the pool of available memory by exactly one call to free().

IO library functions

Math library functions

All of the math.h functions return type double.

Generating random numbers

// to set the seed manually
unsigned int seed = 42; // unsigned implies non-negative
srand(seed);

// to set the seed automatically
srand( time( NULL) ); // need <time.h>

// to generate random numbers
fprintf("%d", rand());

File handling

Data files

Opening and closing files

Opening files

#include <stdio.h>

FILE * filePtr;
filePtr = fopen( "someFilename.xyz", "r" );
// optional: check if file was opened
if ( filePtr == NULL ) {
    printf( "ERROR - file could not be opened!\n" );
}
else{
    // do stuff with the file
    fclose( filePtr );
} 

File open modes

Files and Streams

Standard library functions (in stdio.h)

Example:

#include <stdio.h>
#include <stdlib.h>

int main () {
   char str1[10], str2[10], str3[10];
   int year;
   FILE * fp;

   fp = fopen ("file.txt", "w+");
   fputs("We are in 2018", fp);
   
   rewind(fp);
   fscanf(fp, "%s %s %s %d", str1, str2, str3, &year);
   
   // str1 = "We"
   // str2 = "are"
   // str3 = "in"
   // year = "2018"

   fclose(fp);
   
   return(0);
}

Write to/Read from Binary Files

Eg: fwrite( &myObj, sizeof( egType ), 1, fPtr );

Random-Access Files

Writing Data to a Random-Access File

Sets file position pointer to a specific position

int fseek( FILE *stream, long int offset, int whence );

fwrite( &dataVariableToWrite, sizeof( dataVariable ), 1, filePtr );
fread( &dataVariableToRead, sizeof( dataVariable ), 1, filePtr );
// here 1 is the nr of elements to read; can be something else