A Little C Primer/C Quick Reference

From Wikibooks, open books for an open world
Jump to navigation Jump to search

This section contains a sample program to give syntax examples for fundamental C statements, followed by a list of library routines. This list is very terse and simply provides reminders. If more details are needed, please refer to the previous chapters.

   /* sample.c:  a silly program to give syntax examples. */

   #include <stdio.h>           /* Include header file for console I/O. */

   int f1( int p );             /* Function prototypes. */
   long f2( void );
   long g;                      /* Global variable. */

   void main( int argc, char *argv[] )
     float f;                   /* Declare variables. */
     int ctr;
     extern long g;

     printf( "Arguments:\n\n" );
     for( ctr = 0; ctr < argc; ctr++ )
       puts( argv[ctr] );

     printf( "\nFunction 1:\n\n" );
     ctr = 0;
     while( ctr < 5 ) 
       printf( "%d\n", f1( ctr++ ) ); 

     printf( "\nFunction 2:\n\n" );
     ctr = 0;
       g = ctr++;
       printf( "%d\n", f2( ) );
     while( ctr < 5 );

     exit( 0 );

   int f1( int p ) 
     return( ( p < 3 ) ? p : p p );

   long f2( void )
     extern long g;
     return( g g );

Console I/O -- #include <stdio.h>:

   int printf( char *s, <varlist> ) > 0      Print formatted string to stdout.
   int scanf( char *s, *<varlist> ) != EOF   Read formatted data from stdin.
   int putchar( int ch )                     Print a character to stdout.
   int getchar() != EOF                      Read a character from stdin.
   int puts( char *s )                       Print string to stdout, add \n.
   char *gets() != NULL                      Read line from stdin (no \n).

PC console routines -- #include <conio.h>:

   int getch() != 0           Get a character from the keyboard (no Enter).
   int getche() != 0          Get a character from the keyboard and echo it.
   int kbhit() != 0           Check to see if a key has been pressed.

Format codes:

   %h       short int (scanf() only)
   %d       decimal integer
   %ld      long decimal integer
   %c       character
   %s       string
   %e       exponential floating-point
   %f       decimal floating-point
   %g       use %e or %f, whichever is shorter (printf() only)
   %u       unsigned decimal integer
   %o       unsigned octal integer
   %x       unsigned hex integer

   %10d     10-character field width.
   %-10d    Left-justified field.
   %6.3f    6-character field width, three digits of precision.

   '\0NN'   character code in octal.
   '\xNN'   character code in hex.
   '\0'     null character.

File-I/O -- #include <stdio.h>:

   FILE *fopen( char *f, char *mode ) != NULL           Create or open file.
   int fclose( FILE *f )                                Close a file.

   rewind( FILE *f )                                    Rewind.
   rename( char *old, char *new )                       Rename a file.
   remove( char *name )                                 Delete a file.

   fseek( FILE *f, long offset, int origin) == 0        Seek.

   fprintf( FILE *f, char *fmt, <varlist> ) > 0         Formatted write.
   fscanf( FILE *f, char *fmt, &<varlist> ) != EOF      Formatted read.
   fwrite( void *b, size_t s, size_t c, FILE *f ) > 0   Unformatted write.
   fread( void *b, size_t s, size_t c, FILE *f ) > 0    Unformatted read.

   putc( int c, FILE *f )                               Write character.
   int getc( FILE *f ) != EOF                           Read character.
   fputs( char *s, FILE *f )                            Write a string.
   fgets( char *s, int max, FILE *f) != NULL            Read a string.

   sprintf( char *b, char *fmt, <varlist> )             Print into string.
   sscanf( char *b, char *fmt, &<varlist> ) > 0         Scan string.

File modes:

   r     Open for reading.
   w     Open and wipe (or create) for writing.
   a     Append -- open (or create) to write to end of file.
   r+    Open a file for reading and writing.
   w+    Open and wipe (or create) for reading and writing.
   a+    Open a file for reading and appending.

Offset values:

   SEEK_SET    Start of file.
   SEEK_CUR    Current location.
   SEEK_END    End of file.

Math library -- #include <math.h>:

   double sin( double x )             Sine of x (in radians).
   double cos( double x )             Cosine of x.
   double tan( double x )             Tangent of x.
   double asin( double x )            Inverse sine of x.
   double acos( double x )            Inverse cosine of x.
   double atan( double x )            Inverse tangent of x.
   double sinh( double x )            Hyperbolic sine of x.
   double cosh( double x )            Hyperbolic cosine of x.
   double tanh( double x )            Hyperbolic tangent of x.
   double exp( double x )             Exponential function -- e^x.
   double log( double x )             Natural log of x.
   double log10( double x )           Base 10 log of x.
   double pow( double x, double y )   Power function -- x^y.
   double sqrt( double x )            Square root of x.
   double ceil( double x )            Integer >= x (returned as double).
   double floor( double x )           Integer <= x (returned as double).
   double fabs( x )                   Absolute value of x.

Standard utility library -- #include <stdlib.h>:

   double atof( char *nvalstr ) != 0   Convert numeric string to double.
   int atoi( char *nvalstr )    != 0   Convert numeric string to int.
   long atol( char *nvlastr )   != 0   Convert numeric string to long.
   int rand()                          Generates pseudorandom integer.
   srand( unsigned seed )              Seed random-number generator.
   exit( int status )                  Exits program.
   int system( char *syscmd )   == 0   Execute system program.
   int abs( int n )                    Absolute value of int.
   long labs( long n )                 Absolute value of long.

Time & date library -- #include <time.h>:

   time_t time( time_t *timeptr )      Current time count as long int.
   char *ctime( time_t *timeptr )      Current time & date string.

String function library -- #include <string.h>:

   int strlen( char *s )                           Length.
   strcpy( char *dst, char *src )                  Copy.
   strncpy( char *dst, char *src, size_t n )       Copy n characters max.
   strcat( char *dst, char *s )                    Concatenate.
   strncat( char *d, char *s, size_t n )           Concatenate n characters.
   strcmp( char *s1, char *s2 )             == 0   Compare.
   strncmp( char *s1, char *s2, size_t n )  == 0   Compare n characters.
   stricmp( char *s1, char *s2 )            == 0   Compare, no case.
   strnicmp( char *s1, char *s2, size_t n ) == 0   Compare, no case, n chars.
   char *strchr( char *s, int ch )       != NULL   Find first character.
   char *strrchr( char *s, int ch )      != NULL   Find last character.
   char *strstr( char *dst, char *src)   != NULL   Find string.
   char *strlwr( char *s )                         Lowercase.
   char *strupr( char *s )                         Uppercase.

Character class test library -- #include <ctype.h>:

   int isalnum( int c )  != 0         Alpha / digit.
   int isalpha( int c )  != 0         Alpha.
   int iscntrl( int c )  != 0         Control character.
   int isdigit( int c )  != 0         Decimal digit.
   int isgraph( int c )  != 0         Printing character (except space).
   int islower( int c )  != 0         Lower-case.
   int isprint( int c )  != 0         Printing character (including space).
   int ispunct( int c )  != 0         Printing character but not space/alnum.
   int isspace( int c )  != 0         Space, FF, LF, CR, HT, VT.
   int isupper( int c )  != 0         Upper-case.
   int isxdigit( int c ) != 0         Hex digit.

   int tolower( int c )               Convert to lower case.
   int toupper( int c )               Convert to upper case.

Dynamic memory allocation -- #include <malloc.h>:

   buf = (<type> *)malloc( (size_t)sizeof( <type> ) <array size>) != NULL 
   free( <type> *buf )