% text/plain

 
  % -------------------------------------------
  %  latex generated by: booktolatex.cgi   
  %   from source file : ../htdocs/books/c/c-book.txt       
  %                  on: 27 February 2024,  5:48pm         
  %         querystring: books/c/c-book.txt  
  %       document-root: /var/www/html
  %         script-name: /cgi-bin/booktopdf.cgi
  %         Server-name: bumble.sourceforge.net
  %          Sed-script: booktolatex.sed
  % ------------------------------------------- 

  \documentclass[a4paper,12pt]{article} 
  \usepackage[margin=0.4cm,noheadfoot]{geometry} 
  \usepackage{color}                   %% to use colours, use "xcolor" for more
  \usepackage{multicol}                %% for multiple columns 
  \usepackage{keystroke}               %% for keyboard key images 
  \usepackage[toc]{multitoc}           %% for multi column table of contents
  \usepackage{tocloft}                 %% to customize the table of contents
  \setcounter{tocdepth}{2}             %% only display 2 levels in the contents
  \setlength{\cftbeforesecskip}{0cm}   %% make the toc more compact
  \usepackage{listings}                %% for nice code listings
  %\lstset{language={},
  \lstset{language=c,                 
    %% define special comment delimiters '##(' and ')' 
    moredelim=[s][\color{grey}\itshape\footnotesize\ttfamily]{~(}{)},
    basicstyle=\ttfamily,           %% fixed pitch font
    xleftmargin=1cm,                %% margin on the left outside the frames
    breaklines=true,                %% break long code lines
    breakatwhitespace=false,        %% break long code lines anywhere
    breakindent=10pt,               %% reduce the indent from 20pt to 10
    postbreak=\mbox{{\color{blue}\small$\Rightarrow$\space}},  %% mark with arrow
    showstringspaces=false,            %% dont show spaces within strings 
    framerule=5pt,                     %% thickness of the frames
    rulecolor=\color{lightgrey}, frame=l}   %% source code settings
  \usepackage{graphicx}                %% to include images
  \usepackage{fancybox}                %% boxes with rounded corners 
  \usepackage{wrapfig}                 %% flow text around tables, images 
  \usepackage{tabularx}                %% change width of tables 
  \usepackage[table]{xcolor}           %% alternate row colour tables
  \usepackage{booktabs}                %% for heavier rules in tables 
  \usepackage[small,compact]{titlesec} %% sections more compact, less space
  \usepackage{enumitem}                %% more compact and better lists 
  \setlist{noitemsep}                  %% reduce list item spacing 
  \usepackage{hyperref}     %% make urls into hyperlinks
  \hypersetup{              %% add "pdftex," if only pdf output is required
     colorlinks=true,       %% set up the colours for the hyperlinks 
     linkcolor=black,       %% internal document links black 
     urlcolor=black,        %% url links black 
     filecolor=red,       
     citecolor=red, 
     bookmarks=true, pdfpagemode=UseOutlines} 

  % define some colours to use
  \definecolor{lightgrey}{gray}{0.70}
  \definecolor{grey}{gray}{0.30}

  \titleformat{\section}[frame]    %% titlesec: create framed section headings
     {\normalfont} 
     {\filleft \footnotesize \enspace Section \thesection\enspace\enspace} 
     {3pt} {\bfseries\itshape\filright} 
     
  \title{} 
  \author{}
  \date{22 February 2015, 10:13pm} 
  \setlength{\parindent}{0pt}
  % \setlength{\parskip}{1ex}

  % label lists with stars
  \renewcommand{\labelitemi}{$\star$}

  \begin{document} 

  \centerline{\Large \bf } \medskip
  \begin{center}
    {\huge ``}\textit{}{\huge ''}
    \textsc{}
  \end{center}
  % -----------------------------------
  % the toc should be 2 columns because of the \multitoc package 
  \tableofcontents

   \& The C Programming Language


\begin{description}[labelindent=1cm, leftmargin=2cm, style=nextline]
 \item[\url{http://c-faq.com/}]
     this is essential reading
 \item[\url{http://www.cs.cf.ac.uk/Dave/C/}]
     a badly formatted introduction to c
 \item[\url{nntp://comp.lang.c}]
     to be read regularly
 \item[\url{http://www.iu.hio.no/~mark/CTutorial/CTutorial.html}]
     a pretty basic tutorial about c, doesnt go into dynamic memory
     allocation or anything like that
 \item[\url{http://ee.hawaii.edu/~tep/EE160/Book/}] 
     an online book about c
 \item[\url{http://www.acm.uiuc.edu/webmonkeys/book/c_guide/}]
     not a bad guide to c but pretty old
 \item[\url{http://www.java2s.com/Code/C/CatalogC.htm}]
     lots of example c programs
 \item[\url{http://www.lysator.liu.se/c/pikestyle.html}]
     rob pikes notes on c
\end{description}

\emph{ Possibly the simplest possible c program }
  \begin{lstlisting}
    #include <stdio.h>
    int main () {
      printf ("This is a C program\n");
      return(0);
    }
  \end{lstlisting}

\section{History}

  C was invented, circa 1972, by Denis Ritchie et al, at Bell labs, as part
  of the process of creating the Unix operating system. One of the
  motivations of c was to aleviate the work of porting the Unix operating
  system to new computer architectures. 

\section{Notes}

  C is both a low level and high level computer language. It is the
  original 'write once, compile anywhere' language. C is just high enough
  level to be portable and low enough level to be efficient. C is still the
  most important language for writing virtual machines and operating
  systems.

\section{Api}

\begin{description}[labelindent=1cm, leftmargin=2cm, style=nextline]
 \item[\url{http://www.cppreference.com/wiki/}]
    a complete looking api reference oriented to c++
\end{description}

\emph{ Search for a character within a string }
  \begin{lstlisting}
    #include <wchar.h>
    wchar_t *wcschr(const wchar_t *ws, wchar_t wc);
  \end{lstlisting}

\section{Internationalization}

\subsection{Locales}

\emph{ Set the locale for all categories to the environment of the computer }
\begin{lstlisting}
  setlocale (LC_ALL, ""); ~(the default is the 'c' locale)
\end{lstlisting}
  
\emph{ Find out the current locale }
  \begin{lstlisting}
    #include <locale.h>
    #include <stdio.h>
    int main() {
      printf("Current locale is: %s\n", setlocale(LC_ALL,NULL));
      return 0;
    }
  \end{lstlisting}

\emph{ Show the local before and after setting it to the default  }
  \begin{lstlisting}
    #include <locale.h>
    #include <stdio.h>
    int main() {
      printf("Current locale is: %s\n", setlocale(LC_ALL,NULL));
      setlocale (LC_ALL, ""); 
      printf("Current locale is: %s\n", setlocale(LC_ALL,NULL));
      return 0;
    }
  \end{lstlisting}

\emph{ Set the locale for formatting numbers (but not money) to 'french'; }
  \begin{lstlisting}
    #include <locale.h>
    int main()
    {
      setlocale(LC_NUMERIC, "fr");
    }
  \end{lstlisting}

\emph{ Set the locale for formatting time values to 'spanish' }
\begin{lstlisting}
  setlocale(LC_TIME, "es");
\end{lstlisting}

\begin{description}[labelindent=1cm, leftmargin=2cm, style=nextline]
 \item[\url{http://www.chemie.fu-berlin.de/chemnet/use/info/libc/libc_19.html\#SEC322}]
\end{description}


  \arrayrulecolor{gray}
  \begin{center}
  \begin{tabular}{ |rl| }
    \multicolumn{2}{c}{\textbf{ c locale categories }} \\
  \hline

    \texttt{ LC\_COLLATE } & Collation of strings (eg 'strcoll') \\ 

    \texttt{ LC\_CTYPE } & Classification and conversion of characters (multibyte, wide) \\ 

    \texttt{ LC\_MONETARY } & Formatting monetary value \\ 

    \texttt{ LC\_NUMERIC } & Formatting numbers (not money) \\ 

    \texttt{ LC\_TIME } & Formatting date and time values \\ 

    \texttt{ LC\_ALL } & All categories \\ 

    \texttt{ LANG } & Take local from the enviroment variable \\ 

    \hline
    \end{tabular}
    \end{center}
\emph{ Set the local to the local of the computer }
\begin{lstlisting}
  setlocale(LC_ALL, ""); ~(this must come before any wprintf statement)
\end{lstlisting}

\section{Using International Characters}

\begin{description}[labelindent=1cm, leftmargin=2cm, style=nextline]
 \item[\url{http://triptico.com/docs/unicode.html}] how to convert
 \item[\url{http://www.linux.com/archive/feature/51836}]
\end{description}

   In this day and age using the 'char' character type is simply 
   not good enough. The world has become globalised and text with
   foreign language characters needs to be handled.

\begin{description}[labelindent=1cm, leftmargin=2cm, style=nextline]
 \item[\url{http://www.gnu.org/software/libc/manual/html_node/Extended-Char-Intro.html\#Extended-Char-Intro}]
\end{description}

\emph{ Loop through a (unicode) text file one character at a time }
   \begin{lstlisting}

   /* ?? maybe have to convert the text file first */
   // this is ISO C90 code
   wint_t c;
   while ((c = wgetc (fp)) != WEOF)
   {
   }
   \end{lstlisting}


  \arrayrulecolor{gray}
  \begin{center}
  \begin{tabular}{ |rl| }
    \multicolumn{2}{c}{\textbf{ teminology }} \\
  \hline

  \texttt{ multibyte character } & A character in an encoding like utf8 (variable length) \\ 

  \texttt{ wide character } & A character in ucs-2 or ucs-4 encoding (fixed length) \\ 

    \hline
    \end{tabular}
    \end{center}

  \arrayrulecolor{gray}
  \begin{center}
  \begin{tabular}{ |rl| }
    \multicolumn{2}{c}{\textbf{ wide character conversion functions }} \\
  \hline

  \texttt{ int wctob(wint\_t c) } & Converts a wide char to a single byte (if possible) \\ 

  \texttt{ mbrtowc } & Converts next multibyte char in string to a wide char \\ 

    \hline
    \end{tabular}
    \end{center}
\emph{ Converting a multibyte string (utf8 for example) to a wide character string }
  \begin{lstlisting}

    wchar_t * mbstouwcs(const char *s)
    {
      size_t len = strlen (s);
      wchar_t * result = malloc((len + 1) * sizeof(wchar_t));
      wchar_t * wcp = result;
      wchar_t tmp[1];
      mbstate_t state;
      size_t nbytes;

      memset (&state, '\0', sizeof (state));
      while ((nbytes = mbrtowc (tmp, s, len, &state)) > 0)
        {
          if (nbytes >= (size_t) - 2)
            /* Invalid input string.  */
            return NULL;
          *wcp++ = towupper (tmp[0]);
          len -= nbytes;
          s += nbytes;
        }
      return result;
    }
   \end{lstlisting}

\section{Defining Constant Values}

\emph{ Define a constant variable }
\begin{lstlisting}
  #define ELEMENTSIZE 10 
\end{lstlisting}

\section{Initializing Variables}
  
\emph{ Declare an integer 'i' and an array of 100 integers 'ex' }
\begin{lstlisting}
  int i, ex[100];
\end{lstlisting}

\emph{ Initialise a wide character string 'name' to be empty  }
\begin{lstlisting}
  wchar_t name[200] = { L'\0' };
\end{lstlisting}

\emph{ Initialise all fields of a 'struct tm' to 0 }
\begin{lstlisting}
  struct tm tm; memset(&tm, 0, sizeof(struct tm));
\end{lstlisting}


\section{Switch Statements}

\emph{ A switch statement }
 \begin{lstlisting}
 switch(betty)
 {
  case 1:
    printf("betty=1\n");
     break;
  case 2:
    printf("betty=2\n");
    break;
  default:
    printf("Not sure.\n");
 }
 \end{lstlisting}

\section{Loops}

\emph{ Exit a 'for' or 'while' loop without iterating. }
\begin{lstlisting}
  break;
\end{lstlisting}

\emph{ Execute the next iteration of a for or while loop }
\begin{lstlisting}
  ;
\end{lstlisting}

\section{Infinite Loops}

  An infinite loop has the potential to never terminate.

\emph{ An infinite loop using for }
\begin{lstlisting}
  for (;;) { }
\end{lstlisting}

\emph{ An infinite loop with while }
\begin{lstlisting}
  while (1) { }
\end{lstlisting}

\subsection{While Loops}

  
\section{For Loops}

\emph{ The body of a for loop does not need to have braces $\{$$\}$ around it }
  \begin{lstlisting}
     for ( n = 1; n < index; ++n )
	if ( var->next == NULL )
	    return NULL;
	else
	    var = var->next;
  \end{lstlisting}

\section{Getting Input From The User}

\emph{ Get a line of text from the user, a maximum of 200 wide characters }
  \begin{lstlisting}
    #include <stdio.h>
    #include <wchar.h>
    #include <locale.h>
    int main(void) {
      wchar_t buffer[201] = { L'\0' };
      setlocale(LC_ALL, "");   
      wprintf(L"Enter something, telephone ☎:");
      fgetws(buffer, 200, stdin);
      wprintf(L"You entered: %ls", buffer);
    }
  \end{lstlisting}

  Note that fgetws (like fgetwc, fputwc, and fputws) performs 
  an implicit conversion between multibyte and wide characters.
  How this actually works, I wouldnt know.

\section{Displaying Text}

\begin{description}[labelindent=1cm, leftmargin=2cm, style=nextline]
 \item[\url{http://www.cplusplus.com/reference/clibrary/cstdio/printf/}]
    complete specification for printf
\end{description}

\emph{ Printf is the traditional way. puts }

\emph{ Print a float specifying the output format }
\begin{lstlisting}
  printf("%6.3f", 2.8)       ~(prints '2.800')
\end{lstlisting}

\emph{ Print a string left justified, field width 4 }
\begin{lstlisting}
  printf "%-4s", "foo";      ~(prints "foo ")
\end{lstlisting}
\begin{lstlisting}
  int swprintf(wchar_t *wcs, size_t maxlen, const wchar_t *format, ...);
\end{lstlisting}

\emph{ Print a number padded on the left by zeros  }
\begin{lstlisting}
  printf("%04d", i);
\end{lstlisting}

\emph{ Use an inspection set }
\begin{lstlisting}
  scanf("%[A-Z:]", stdin);
\end{lstlisting}
\begin{lstlisting}
  wscanf(L"%l[A-Z:]", stdin);
\end{lstlisting}

\emph{ Print 'pi' to five decimal places }
  \begin{lstlisting}

    #include <math.h>
    #include <stdio.h>
    fprintf(stdout, "pi = %.5f\n", 4 * atan(1.0));
  \end{lstlisting}

\section{Strings}
 
  This section deals with wide character string 'wchar\_t *' and with byte
  array strings 'char *'. Wide character strings should be able to handle
  characters outside of the standard 'ascii' (roman alphabet) characters,
  which is important.

  It is not possible to mix the use of 'printf' and 'wprintf' in the same
  program That is, any stream is either wide oriented or byte oriented.
  'fwide()' can determine which it is. Whichever function is used first
  determines the nature of the streams (including 'stdin', 'stdout', 'stderr')

\subsection{Initialising Strings}

\emph{ Initialise a char string using compiler concatenation }
\begin{lstlisting}
  char story[] = "once apon a time"
\end{lstlisting}
      ``there was a small tree'';

\emph{ Define, initialize, print a wide character string }
  \begin{lstlisting}
   #include <locale.h>
   #include <wchar.h>
   main () {
     wchar_t message[] = L"xx雨が降りそうxx\n";
     setlocale(LC_ALL, "");   
     wprintf (L"message:%ls\n", message);
   }
  \end{lstlisting}

\emph{ Define, initialize, print a wide character string }
  \begin{lstlisting}
   #include <locale.h>
   #include <wchar.h>
   main () {
     wchar_t message[100];
     setlocale(LC_ALL, "");   
     wcscpy (message, L"雨が降りそう hello\n");
     wprintf (L"message:%ls\n", message);
   }
  \end{lstlisting}

\emph{ Define and print a wide character  }
  \begin{lstlisting}
   #include <locale.h>
   #include <wchar.h>
   main () {
     wchar_t kanji = L'雨';
     setlocale(LC_ALL, "");   
     wprintf (L"kanji:%lc\n", kanji);
     wprintf (L"decimal:%i\n", kanji);
     wprintf (L"unicode code point:%x\n", kanji);
   }
  \end{lstlisting}

\emph{ Define a kanji using \textbackslash uxxxx notation (c99, c++ only) }
  \begin{lstlisting}
   #include <locale.h>
   #include <wchar.h>
   main () {
     wchar_t k = L'\u96ea';
     setlocale(LC_ALL, "");   
     wprintf (L"kanji:%lc, decimal:%i, unicode:%x\n", k,k,k);
   }
  \end{lstlisting}

\subsection{Manipulating Strings}

\emph{ Remove the last character from the string 'line' }
\begin{lstlisting}
  *(line+strlen(line)-1) = '\0';
\end{lstlisting}

\subsection{Copying}

\emph{ Copy a byte string into another  }
  \begin{lstlisting}
   #include <stdio.h>
   #include <string.h>
   int main () {
     char name[100] = "john";
     char tag[100];
     strcpy (name, L"雨が降りそう hello\n");
     printf ("name= %s\n", );
   }
  \end{lstlisting}

\emph{ Copy a wide character string into another  }
  \begin{lstlisting}
   #include <wchar.h>
   #include <locale.h>
   int main () {
     wchar_t name[100] = L"john";
     wchar_t tag[100];
     setlocale (LC_ALL, ""); 
     wcscpy(name, L"雨が降りそう hello\n");
     wcscpy(tag, L"雨が降りそう hello\n");
     wprintf(L"name:%ls\n", name);
     return(0);
   }
  \end{lstlisting}

\subsection{Size}

\emph{ Display the size of a wide string  }
  \begin{lstlisting}
   #include <wchar.h>
   #include <locale.h>
   int main () {
     wchar_t name[100] = L"x雨が降りそx";
     setlocale (LC_ALL, ""); 
     wprintf(L"name:%ls\n", name);
     wprintf(L"size (bytes):%d\n", sizeof(name));
     wprintf(L"size (chars):%d\n", sizeof(name)/sizeof(wchar_t));
     wprintf(L"length (chars):%d\n", wcslen(name));
     return(0);
   }
  \end{lstlisting}

  Before appending something to a string in c, it is always necessary
  to make sure that there is enough room in the buffer. This can be
  done with 'sizeof'

\emph{ Display the size of a wide string pointer, this doesnt work }
  \begin{lstlisting}
   #include <wchar.h>
   #include <locale.h>
   int main () {
     wchar_t n[100] = L"x雨が降りそx";
     wchar_t * p = n + 3; 
     setlocale (LC_ALL, ""); 
     wprintf(L"n:%ls\n", n);
     wprintf(L"p:%ls\n", p);
     wprintf(L"size n (bytes):%d\n", sizeof(n));
     wprintf(L"size p (bytes):%d\n", sizeof(p));
     wprintf(L"size (chars):%d\n", sizeof(n)/sizeof(wchar_t));
     wprintf(L"length (chars):%d\n", wcslen(n));
     return(0);
   }
  \end{lstlisting}
  
  The code above shows that a string defined with 'char s[n]' knows how
  big it is, but a pointer defined with 'char * s' doesnt know how 
  big the string is.

\subsection{Reading}

\emph{ Read a line of (maximum 64) wide characters from the keyboard  }
  \begin{lstlisting}
   #include <wchar.h>
   #include <locale.h>
   int main () {
     wchar_t name[64] = L"X";
     setlocale (LC_ALL, ""); 
     wprintf(L"Enter name: ");
     int results = wscanf(L"%63l[^\n]", name); 
     wprintf(L"Name:%ls\n", name);
     return(0);
   }
  \end{lstlisting}

\emph{ Read two words from the user and store them in variables  }
  \begin{lstlisting}
   #include <wchar.h>
   #include <locale.h>
   int main () {
     wchar_t fname[64] = {L'\0'};
     wchar_t lname[64] = {L'\0'};
     setlocale (LC_ALL, ""); 
     wprintf(L"Enter first and last name: ");
     int results = wscanf(L"%63ls%63ls", fname, lname); 
     wprintf(L"first:%ls last:%ls\n", fname, lname);
     return(0);
   }
  \end{lstlisting}

\subsection{Displaying Strings}

\emph{ Query if output stream is wide oriented ($>$0) or not }
\begin{lstlisting}
  if (fwide(stdout, 0) == 0) ...
\end{lstlisting}

   print a byte string with wprintf
   \begin{lstlisting}
     #include <locale.h> 
     int main() {
       char * s = "test";
       wprintf(L"ascii string: %s\n", s);
     }
   \end{lstlisting}

\emph{ Define and initialise to empty a wide character string }
\begin{lstlisting}
  wchar_t buffer[200] = { L'\0' };
\end{lstlisting}
\begin{lstlisting}
  wchar_t buffer[200]; buffer[0] = 0; ~(another way)
\end{lstlisting}

\emph{ Print a wide character string }
\begin{lstlisting}
  wprintf (L"value: %ls\n");
\end{lstlisting}

\subsection{Analysing Strings}

 
\emph{ A simple 'startsWith' function, untested }
  \begin{lstlisting}
  bool prefix(const char *prefix, const char *str)
  {
    return strncmp(pre, str, strlen(prefix)) == 0;
  }
  \end{lstlisting}

\subsection{Searching Strings}

  search a string for a particular character
  \begin{lstlisting}
    #include <stdio.h>
    #include <string.h>
    int main (void)
    {
      char * p; char c = 'x';
      p = strchr("some text to be searched", c);
      if (p == NULL)
        { printf("character not found"); }
      printf(p);
      return(0);
    }
  \end{lstlisting}

\subsection{Errors With Strings}

\emph{ ``error: invalid initializer'' }
\begin{lstlisting}
  wchar s[10] = "wrong";  ~(incorrect!!)
\end{lstlisting}
\begin{lstlisting}
  wchar s[10] = L"wrong";
\end{lstlisting}

\section{Booleans}
  
  The c language treats the value 0 as false and all
  non-zero values as true, but a boolean 'type' was not 
  traditionally part of the c language.

\emph{ Define an enumerated type for booleans }
\begin{lstlisting}
  enum Bool { FALSE=0, TRUE };
\end{lstlisting}
  
\emph{ Using booleans }
  \begin{lstlisting}
    #include <stdbool.h> 
    _Bool isHot;
  \end{lstlisting}

\emph{ Define a boolean and display its value }
  \begin{lstlisting}
    #include <stdio.h>
    #include <stdbool.h>
    main()
    {
      bool isHot = false;
      printf("isHot:%s", isHot?"true":"false");
    }
  \end{lstlisting}

\emph{ Define a boolean and display its value as a wide string }
  \begin{lstlisting}
    #include <stdio.h>
    #include <stdbool.h>
    #include <locale.h>
    int main()
    {
      bool isHot = false;
      setlocale (LC_ALL, ""); 
      wprintf(L"isHot:%ls", isHot?L"true":L"false");
      return(0);
    }
  \end{lstlisting}

\section{Multibyte And Wide Strings}

 A multibyte string is something like utf8. In these encodings
 a character may occupy 1, 2 or more bytes. This is called a
 variable length encoding. Wide character characters have fixed
 length (usually 4 bytes).

\subsection{Implicit Conversion}

  use fgetwc, fgetws, fputwc, fputws.

\subsection{Explicit Conversion}

\emph{ Convert some input text from multibyte to wide character }
\begin{lstlisting}
  fgets(s2, BUFSIZ, stdin);   /* read EUC string from stdin into s2 */
\end{lstlisting}
\begin{lstlisting}
  mbstowcs(s1, s2, BUFSIZ);   /* convert EUC string in s2 to process
\end{lstlisting}
                                      code string in s1 */

\subsection{Screen Width}

\begin{lstlisting}
  int wcswidth (const wchar_t *s, size_t n); 
\end{lstlisting}

\subsection{Initialising String Variables}

\emph{ Define and initialise a wide character string }
\begin{lstlisting}
  wchar_t text[100] = L"This is unicode, rain 雨";
\end{lstlisting}

\emph{ Initialise a wide string to be 'empty' }
\begin{lstlisting}
  wchar_t text[50] = L"";
\end{lstlisting}
\begin{lstlisting}
  wchar_t text[50] = {L'\0'};   ~(the same)
\end{lstlisting}

\emph{ Define and initialise as empty a string with a capacity of 19 }
\begin{lstlisting}
  wchar_t s[20]; *s = L'\0';
\end{lstlisting}
\begin{lstlisting}
  wchar_t s[20]; *s = 0;        ~(the same ?)
\end{lstlisting}

\subsection{Comparing Strings}

\emph{ Test if the string variable is ``snow'' }
\begin{lstlisting}
  if (wcscmp(word, L"snow") == 0)
\end{lstlisting}

\emph{ Compare two wide strings  }
  \begin{lstlisting}
    #include <stdio.h>
    #include <locale.h>
    #include <wchar.h>
    int main()
    {
      wchar_t * s = L"雨雨雨";
      wchar_t * t = L"雨雨雨";
      setlocale (LC_ALL, ""); 
      if (!wcscmp(s, t))
        wprintf(L"strings are equal\n");
      else
        wprintf(L"strings are not equal\n");
      return(0);
    }
  \end{lstlisting}

  http://www.chemie.fu-berlin.de/chemnet/use/info/libc/libc\_5.html\#SEC61

\emph{ Duplicate a string     }
\begin{lstlisting}
  strdup
\end{lstlisting}

\emph{ Add a character to a string }
\begin{lstlisting}
  sprintf(s, "%s%c", s, c);
\end{lstlisting}

\section{Time And Date}

  use clock() to time the amount of time it takes
  execute some section of code.


  use gmtime() etc to get calender dates.

\emph{ Get help for the time() function }
\begin{lstlisting}
  man 2 time
\end{lstlisting}

\emph{ Print the current date and time }
  -----
    include $<$stdio.h$>$
    include $<$time.h$>$
    int main() $\{$
      time\_t now = time(NULL);
      // or time\_t now; time(\&now);
      printf(``the date is now: \%s'', ctime(\&now));
    $\}$
  ,,,

\emph{ Determine if a date is today  }
  -----
    include $<$stdio.h$>$
    include $<$time.h$>$
    int main() $\{$
      struct tm someday = $\{$1,1,1,28,2,114,-1,-1,-1$\}$;
      time\_t now; time(\&now);
      struct tm today = *localtime(\&now);
       
      printf(``today is: \%s'', asctime(\&today));
      printf(``someday is: \%s'', asctime(\&someday));
      if (today.tm\_year == someday.tm\_year \&\&
          today.tm\_mon == someday.tm\_mon \&\&
          today.tm\_mday == someday.tm\_mday)
        printf(``someday is today!!!'');
    $\}$
  ,,,

\emph{ Get the current year  }
  -----
    include $<$stdio.h$>$
    include $<$time.h$>$
    int main() $\{$
      time\_t now; time(\&now);
      struct tm date = *localtime(\&now);
      printf("the current year: \%d\textbackslash n", date.tm\_year + 1900);
      printf("the current year: \%d\textbackslash n", localtime(\&now)-$>$tm\_year + 1900);
    $\}$
  ,,,

\emph{ Print the time zone. }
  -----
    include $<$stdio.h$>$
    include $<$time.h$>$
    int main() $\{$
      time\_t now = time(NULL);
      printf(``now the date is: \%s'', ctime(\&now));
      printf(``the time zone is: \%s'', localtime(\&now)-$>$tm\_zone);
    $\}$
  ,,,

\subsection{Strftime}

\emph{ Print a nicely formatted date with strftime  }
  -----
    include $<$stdio.h$>$
    include $<$time.h$>$
    int main() $\{$
      time\_t now = time(NULL);
      char display[200];
      strftime(display, 199, ``\%d/\%m/\%Y \%H:\%M'', localtime(\&now));
      printf(``now the date is: \%s'', display);
      printf(``the time zone is: \%s'', localtime(\&now)-$>$tm\_zone);
    $\}$
  ,,,

  
\subsection{Gotchas}

   months tm.tm\_mon are 1 based.
   years are 1900 based. days of months are 0 based

   negative and out of range integers within a 'struct tm' time
   structure will create havoc with functions such as 'mktime' and
   'strftime'
   
\emph{ Cause a segmentation fault! }
   -----
     struct tm someday = $\{$-1,-1,-1,0,50,1000,0,0,0$\}$;
     char output[200];
     strftime(output, ``\%M, \%Y'', \&tm);
   ,,,

\subsection{Parsing Dates And Times}

  The function 'strptime' carries out the job of parsing
  a date and or time from a character string.

\emph{ Get help for the strptime function }
\begin{lstlisting}
  man strptime
\end{lstlisting}

\emph{ The prototype for strptime }
\begin{lstlisting}
  char *strptime(const char *s, const  char  *format, struct tm *tm);
\end{lstlisting}


  \arrayrulecolor{gray}
  \begin{center}
  \begin{tabular}{ |rl| }
    \multicolumn{2}{c}{\textbf{ some strptime format string example }} \\
  \hline

  \texttt{ \%d/\%m\%/Y } & 31/2/2012  \\ 

    \hline
    \end{tabular}
    \end{center}
  If strptime cant use the format it is given to parse a 
  date then the return char * will be NULL.

\emph{ Parse a date string using strptime  }
  -----
    include $<$stdio.h$>$
    include $<$time.h$>$
    int main() $\{$
      char * remainder; 
      char * input = ``29/6/2015 tuesday'';
      struct tm someday = $\{$-1,-1,-1,0,0,0,-1,-1,-1$\}$;
      remainder = (char *)strptime(input, ``\%d/\%m/\%Y'', \&someday);
      printf(``parsed date: \%s'', asctime(\&someday));
      printf(``remainder: \%s'', remainder);
    $\}$
   ,,,

  The strptime function below correctly fills in the 
  'day of the week' field in the struct tm time\&date structure.
  Neither \%z nor \%Z seems to be working for 'EST' timezone

\emph{ Parse a date and time using strptime  }
  -----
    include $<$stdio.h$>$
    include $<$time.h$>$
    int main() $\{$
      char * remainder; 
      char * input = ``10/4/2014 11:30:00 EST'';
      struct tm someday = $\{$-1,-1,-1,0,0,0,-1,-1,-1$\}$;
      remainder = 
        (char *)strptime(input, ``\%d/\%m/\%Y \%H:\%M:\%S \%Z'', \&someday);
      printf(``parsed date: \%s'', asctime(\&someday));
      printf(``remainder: \%s'', remainder);
    $\}$
   ,,,

\emph{ Parse 2 dates using strptime  }
  -----
    include $<$stdio.h$>$
    include $<$time.h$>$
    int main() $\{$
      char * remainder; 
      char * input = "10/4/2014 11:30:00 - 11/4/2014 12:00:00 ";
      struct tm someday = $\{$-1,-1,-1,0,0,0,-1,-1,-1$\}$;
      struct tm someday2 = $\{$-1,-1,-1,0,0,0,-1,-1,-1$\}$;
      input = 
        (char *)strptime(input, ``\%d/\%m/\%Y \%H:\%M:\%S'', \&someday);
      printf(``1st parsed date: \%s'', asctime(\&someday));
      printf(``remainder: \%s\textbackslash n'', input);
      input = 
        (char *)strptime(input, `` - \%d/\%m/\%Y \%H:\%M:\%S'', \&someday2);
      printf(``2nd parsed date: \%s'', asctime(\&someday2));
      printf(``remainder: \%s\textbackslash n'', input);
    $\}$
   ,,,

\section{Library Functions}

\emph{ View c library functions (on a unix-like operating system) }
\begin{lstlisting}
  man 3 func
\end{lstlisting}

\section{Arrays}

  The name of an array is a pointer to that array, except in the 
  case where the 'sizeof' operator is used.

\emph{ Declare and initialize an integer array., }
  \begin{lstlisting}
    #include <stdio.h>
    int main ()
    {
      int items[] = {32, 43, 29, 0};
      printf ("The first item is %d\n", items[0]);
      printf ("The second item is %d\n", items[1]);
      return(0);
    }
  \end{lstlisting}

\subsection{Initialising Arrays}

\emph{ All elements not initialised are set to '0'  }
\begin{lstlisting}
  long name[100] = {1,3,5,7};
\end{lstlisting}

\subsection{Size Of}

\emph{ Display the size of an array }
  \begin{lstlisting}
   #include <wchar.h>
   #include <locale.h>
   int main () {
     long name[100] = {1,3,5,7};
     setlocale (LC_ALL, ""); 
     wprintf(L"size (bytes):%d\n", sizeof(name));
     wprintf(L"size (elements):%d\n", sizeof(name)/sizeof(long));
     return(0);
   }
  \end{lstlisting}

\emph{ Declare and initialize an array of structures }
  \begin{lstlisting}
   #include <wchar.h>
   #include <locale.h>
   struct {
     int x;
     int y;
   } points[] = {0,1,2,3};

   int main () {
     long name[100] = {1,3,5,7};
     setlocale (LC_ALL, ""); 
     wprintf(L"size (bytes):%d\n", sizeof(name));
     wprintf(L"size (elements):%d\n", sizeof(name)/sizeof(long));
     return(0);
   }
  \end{lstlisting}

\emph{ Declare an array of structures }
\begin{lstlisting}
  struct { int x; int y; } points[] = {{0,1},{2,3}};
\end{lstlisting}

\emph{ Make an array of float types }
  \begin{lstlisting}
    #include <stdio.h>
    #define SIZE 3
    int main (void)
    {
      float x[SIZE];
      float *fp; int i;
      for (i = 0; i < SIZE; i++)
        { x[i] = 0.5 * (float) i; }
      for (i = 0; i < SIZE; i++)
        { printf("  %d  %f \n", i, x[i]); }
      fp = x;
      for (i = 0; i < SIZE; i++)
        printf("  %d  %f \n", i, *(fp + i));
    }

   \end{lstlisting}

\section{Input And Output}

\subsection{Printf}


  \arrayrulecolor{gray}
  \begin{center}
  \begin{tabular}{ |rl| }
    \multicolumn{2}{c}{\textbf{ format specifiers for printf }} \\
  \hline

  \texttt{ \%s } & Any space delimited string \\ 

  \texttt{ \%127s } & A string, maximum of 127 characters \\ 

  \texttt{ etc } \\ 

    \hline
    \end{tabular}
    \end{center}
\emph{ Using compiler string concatenation }
  ------
    printf(
      ``name: \%s\textbackslash n''
      ``age: \%d\textbackslash n'', name, age);
  ,,,

SCANF AND FRIENDS ...

  Scanf is a method of reading formatted textual input into
  c variables. In a basic sense, it 'parses' text input.


  \arrayrulecolor{gray}
  \begin{center}
  \begin{tabular}{ |rl| }
    \multicolumn{2}{c}{\textbf{ format specifiers for scanf, sscanf, fscanf }} \\
  \hline

  \texttt{ \%s } & Any space delimited string \\ 

  \texttt{ \%127s } & A string, maximum of 127 characters \\ 

  \texttt{ \%*127s } & A 127 char string, discard result  \\ 

  \texttt{ \%[\^{}\textbackslash n] } & An entire line \\ 

  \texttt{ \%[abc] } & A string containing only chars a,b or c \\ 

    \hline
    \end{tabular}
    \end{center}
  scanf, sscanf, wscanf etc

  - all variables to scanf must be pointers.
  - whitespace is ignored, except by \%c

\emph{ Read text and a number into variables  }
  ----
    include $<$stdio.h$>$
    int main() $\{$
      int age = 0; char name[128]; 
      printf("enter name and age:\textbackslash n");
      scanf(``\%s\%d'', name, \&age);
      printf("name:\%s, age:\%d \textbackslash n", name, age);
    $\}$
  ,,,

  field widths are useful for limited the number of 
  characters read into a character array.

\emph{ Only read 31 characters into 'city' variable }
  \begin{lstlisting}
    char city[32];
    printf("city: ");
    if (scanf("%31s", city) < 1)
      fprintf(stderr, "error"\n);
  \end{lstlisting}

\emph{ Read and discard the next 5 characters rom the input  }
\begin{lstlisting}
  scanf("%*5c);
\end{lstlisting}

  \%s only read one 'whitespace' delimited word. use
   fgets() to read one whole line.
  
\emph{ Read a text file word by word }
  ----
    include $<$stdio.h$>$
    int main() $\{$
      char word[128];
      FILE * fp = stdin;
      while (fscanf(fp, ``\%127s'', word) == 1) $\{$
        printf(``\%s\textbackslash n'', word);
      $\}$
    $\}$
  ,,,

\emph{ A simple 'interpreter' loop with scanf  }
  ----
    include $<$stdio.h$>$
    int main() $\{$
      char line[128];
      while (1) $\{$
        scanf("\%127[\^{}\textbackslash n]\%*c", line);
        printf(``\%s\textbackslash n'', line);
        if (strcmp(line, ``quit'') == 0) exit(1);
      $\}$
    $\}$
  ,,,

\emph{ Use a 'scanset' or 'inspection set' to read binary }
  ---
    char number[32];
    scanf(``\%31[01]'', number);
  ,,,

  will read at most 31 zeros and ones stopping at the
  first character which is not a '0' or '1'

\emph{ Inverted scanset, reads anything up to 1st punctuation }
\begin{lstlisting}
  scanf("%[^.!?]", sentence);
\end{lstlisting}

  The above example also reads whitespace.

\emph{ Read and discard everything up to the newline }
\begin{lstlisting}
  scanf("%*[^\n]%*c");
\end{lstlisting}
  
  the \%*c reads and discards the \textbackslash n newline in the 
  above example.

\subsection{Wscanf}

  wscanf is used to read 'wide' character strings from
  an input source. This means any character which cannot
  by accomodated by the extended ascii (1 byte) characters.

\emph{ Read a line of (maximum 64) wide characters from the keyboard  }
  \begin{lstlisting}
   #include <wchar.h>
   #include <locale.h>
   int main () {
     wchar_t name[64] = L"X";
     setlocale (LC_ALL, ""); 
     wprintf(L"Enter name: ");
     int results = wscanf(L"%63l[^\n]", name); 
     wprintf(L"Name:%ls\n", name);
     return(0);
   }
  \end{lstlisting}

\section{Reading And Writing Files}

    

  \arrayrulecolor{gray}
  \begin{center}
  \begin{tabular}{ |rl| }
    \multicolumn{2}{c}{\textbf{ legal modes for opening files }} \\
  \hline

    \texttt{ r } & Open text file for reading  \\ 

    \texttt{ w } & Create a text file for writing  \\ 

    \texttt{ a } & Append to text file  \\ 

    \texttt{ rb } & Open binary file for reading  \\ 

    \texttt{ wb } & Create binary file for writing  \\ 

    \texttt{ ab } & Append to a binary file  \\ 

    \texttt{ r+ } & Open text file for read/write  \\ 

    \texttt{ w+ } & Create text file for read/write  \\ 

    \texttt{ a+ } & Open text file for read/write  \\ 

    \texttt{ rb+ or r+b } & Open binary file for read/write  \\ 

    \texttt{ wb+ or w+b } & Create binary file for read/write  \\ 

    \texttt{ ab+ or a+b } & Open binary file for read/write  \\ 

    \hline
    \end{tabular}
    \end{center}
\emph{ Read a text file character by character.,   }
  \begin{lstlisting}

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

    int main (int argc, char *argv[])
    {
      FILE *fp;
      char ch;
      if ((fp = fopen (argv[1], "r")) == NULL)
      {
        printf ("Cannot open file.\n");
        exit (1);
      }
      while ((ch = fgetc (fp)) != EOF)
        { printf ("%c", ch); }
      fclose (fp);
      return 0;
    }
   \end{lstlisting}

\emph{ Open the text 'somefile' file for writing., }
  \begin{lstlisting}
    #include <stdio.h>
    #include <stdlib.h>
    int main (int argc, char *argv[]) {
      FILE *fp;
      if ((fp = fopen ("somefile.txt", "w")) == NULL) {
        printf ("Cannot open file.\n");
        exit (1);
      }
      fclose (fp);
    }
  \end{lstlisting}

  
\emph{ Read the textfile line by line }
  \begin{lstlisting}
    #include <stdio.h>
    #include <stdlib.h>
    int main(int argc, char *argv[]) {
      FILE *fp; char line[1000];
      char * file = "/home/mjb/sf/htdocs/app/data.txt";
      if ((fp = fopen (file, "r")) == NULL) {
        perror("couldnt open file:");
        exit (1);
      }
      while (fgets(line, 999, fp) != NULL)
        printf("%s", line);
      fclose (fp);
    }
  \end{lstlisting}

\subsection{Quirks}

  puts seems to convert the \textbackslash 0 to a \textbackslash n.
\section{Functions}

\emph{ Define a function before the main method }
  \begin{lstlisting}

    #include <stdio.h>
    int sum (int i1, int i2, int i3) {
      return (i1 + i2 + i3);
    }

    int main() {
      printf ("Sum is %d\n", sum (1, 2, 3));
      return (0);
    }
  \end{lstlisting}

\emph{ Define a function with a prototype., }
  \begin{lstlisting}
    //prototypes allow functions to be defined after they are used
    #include <stdio.h>
    int f (void);
    int main (void) {
      int number; 
      number = f(); printf ("%d", number);
      return 0;
    }
    int f (void)
     { return 10; }
  \end{lstlisting}

\subsection{Funtion Pointers}

   Function pointers are interesting and useful. They all functions to
   be passed as parameters to other functions, or to be contained as
   fields in structures or elements of arrays.
  
\emph{ Basic usage }
   -------
     int sum(int a, int b) $\{$ return a + b; $\}$
     int (*fp)(int, int);
     fp = sum;
   ,,,

   above a function and pointer to that function are 
   defined.
   
   The name of the function 'sum' with no parenthesis   is resolved by the compiler as a pointer.
\begin{lstlisting}
  &sum may also work???
\end{lstlisting}

\emph{ Execute a a function pointed to by pointer 'array.fn' }
\begin{lstlisting}
  info.fn(&list, param);
\end{lstlisting}

   In the example above the function pointer is a member of 
   a structure 'info'
  
\section{Structures}

  Structures allow data within a program to be organized in a
  logical manner. Structures are essentially the precursor of
  'objects' in modern object oriented languages. C was
  written to implement Unix in a more portable fashion.
  Possibly the most important features of the C language are
  its inclusion of structures and pointers which make it an
  effective language.  Structures and dynamic memory
  allocation can be used to create standard data structures
  such as linked lists, binary trees and dynamic stacks.

  Since c is 'pass by value' structures passed to functions
  are copied.  To avoid this (inefficient) process, use a
  pointer to the structure instead. Unlike arrays, the name
  of a structure is not a pointer to that structure (I
  think).

\emph{ Defining and using a normal structure }
  \begin{lstlisting}
    #include <stdio.h>
    struct point { int x; int y; };

    int main() {
      struct point p;
      p.x = 3; p.y = 4;
      printf("The point is (%d, %d)\n", p.x, p.y);
      return(0);
    }
  \end{lstlisting}

\emph{ Define a structure and initialise an array of them }
  \begin{lstlisting}
    struct song 
    {
      wchar_t title[100];
      wchar_t singer[100];
    } songlist[] = {
      {L"one too many mornings", L"dylan"},
      {L"money for nothing", L"knoffler"}
      {L"somewhere", L"anon"}
    };
  ,,,, 

  * define and use a typedef structure.,
  \begin{lstlisting}
    typedef struct point {
      int x;
      int y;
    };

    point p, q;
    int main() {
      p.x = 3; p.y = 4;
      printf ("The point is (%d, %d)\n", p.x, p.y);
      return (0);
    }
   \end{lstlisting}

  The technique below is
\begin{lstlisting}
  p = (struct point){3, 4};
\end{lstlisting}
  and it seems to rely on syntax introduced in C99.

\emph{ Initialize a struct after it is declared  }
  \begin{lstlisting}
    #include <stdio.h>
    struct point { int x, y; };
    int main() {
      struct point p;
      p = (struct point){ 3, 4 };
      printf ("The point is (%d, %d)\n", p.x, p.y);
      return (0);
    }
   \end{lstlisting}

\emph{ Define a structure type and variables in one go }
  \begin{lstlisting}
   struct student {
     char name[30];  
     float number;
   } rob, sarah;
  \end{lstlisting}

\emph{ Allocate memory for a structure }
  \begin{lstlisting}
    struct person * p;
    p = (struct person *) malloc(sizeof(struct person);
  \end{lstlisting}

\section{Unions}

 Below... a good example of using a union within a structure 
 with a tag. the enum Type could be within the structure like 
 this

enum Type $\{$ INTS, FLOATS, DOUBLE $\}$;
struct S
$\{$
  Type s\_type;
  // or enum Type $\{$ INTS, FLOATS, DOUBLE $\}$ s\_type;
  union
  $\{$
    int s\_ints[2];
    float s\_floats[2];
    double s\_double;
  $\}$;
$\}$;

void do\_something(struct S *s)
$\{$
  switch(s-$>$s\_type)
  $\{$
    case INTS:  // do something with s-$>$s\_ints
      break;

    case FLOATS:  // do something with s-$>$s\_floats
      break;

    case DOUBLE:  // do something with s-$>$s\_double
      break;
  $\}$
$\}$

\section{Data Structures}

\subsection{Linked Lists}
   
\emph{ A structure which contains a pointer to itself }
   --------
   struct node $\{$
     char *item;
     struct node *next;
   $\}$;
                                                                          typedef struct node *NODEPTR;
   ,,,

\emph{ A linked list implementation.. }
  \begin{lstlisting}

    struct person
    {
      wchar_t name[20];
      int age;
      struct person *next;
    };

    int main()
    {
      struct person * someone;
      struct person * someoneelse;
    }
  \end{lstlisting}

  The above linked list doesnt work very well because
  it is difficult to dynamically create list items.

\emph{ A better linked list implementation.. }
  \begin{lstlisting}

    struct person
    {
      wchar_t * name;
      int age;
      struct person *next;
    };

    struct person * person();

    int main()
    {
      struct person * someone;
      struct person * someoneelse;
    }
  \end{lstlisting}

\section{Object Oriented Programming In C}

\emph{ ?? }

\section{Organising C Code}

\begin{description}[labelindent=1cm, leftmargin=2cm, style=nextline]
 \item[\url{http://tldp.org/HOWTO/Program-Library-HOWTO/more-examples.html}]
\end{description}

\emph{ C files can be organised in modules, with header files }
  \begin{lstlisting}

    /* file: test.c */
    #include <stdio.h>
    #include "header.h"
    char * AnotherString = "Hello Everyone";

    main ()
    {
      printf("running test.c...\n");
      ffTest(TEXT);
      printf("Finished.\n");
    }

    /* file: ffTest.c */
    #include <stdio.h>
    extern char *AnotherString;
    void ffTest(char * s)
    {
      printf("%s\n", s);
      printf("Global Variable = %s\n", AnotherString);
    }

    /* file header.h: */

    #define TEXT "Hello World"
    void ffTest();
  \end{lstlisting}

\subsection{Header Files}

  use ifndef to not include header files twice
  \begin{lstlisting}

   /* File foo.h  */
   #ifndef FOO_H_SEEN
   #define FILE_FOO_SEEN
     ... head file contents
   #endif 
  \end{lstlisting}

\emph{ An example header file }
  \begin{lstlisting}
   #ifndef MY_HEADER
   #define MY_HEADER
     void myfunc1(int a,int b);
     int blah(void);
   #endif
  \end{lstlisting}

\emph{ Declarations can be without parameter names }
\begin{lstlisting}
  int isLeapYear(int);
\end{lstlisting}

\section{One Liners}

\emph{ Execute a shell or system command }
\begin{lstlisting}
  system(...);
\end{lstlisting}

\section{Sockets And Tcp}

  BSD Sockets are the unix and c abstraction for the creation
  of network connections using various protocols- tcp, udp
  etc. 

\emph{ See some documentation for the socket() function }
\begin{lstlisting}
  man socket
\end{lstlisting}


  \arrayrulecolor{gray}
  \begin{center}
  \begin{tabular}{ |rl| }
    \multicolumn{2}{c}{\textbf{ type of sockets }} \\
  \hline

  \texttt{ SOCK\_STREAM } & Tcp/ip \\ 

  \texttt{ SOCK\_DGRAM } & Udp \\ 

  \texttt{ RAW? } & Raw \\ 

    \hline
    \end{tabular}
    \end{center}
\emph{ A simple daytime client using bsd sockets }
  -------
   include $<$sys/socket.h$>$
   include $<$arpa/inet.h$>$
   include $<$stdio.h$>$
   include $<$unistd.h$>$
   include $<$time.h$>$
   include $<$string.h$>$
   define PORT 13
   int main() $\{$
     int con, in, index=0, limit=128;
     struct sockaddr\_in servaddr;
     char output[200];
     
     memset(\&servaddr, 0, sizeof(servaddr));
     servaddr.sin\_family = AF\_INET;
     servaddr.sin\_port = htons(PORT);
     servaddr.sin\_addr.s\_addr = inet\_addr(``127.0.0.1'');
     connect(con, (struct sockaddr *)\&servaddr, sizeof(servaddr));
     while ((in = read(con, \&output[index], 128))$>$0) $\{$
       index += in; limit -= in;
     $\}$
     output[index] = 0;
     printf(``\%s\textbackslash n'', output);
     close(con);
     return(0);
   $\}$
  ,,,

   'htons' is used to set the server port address because 
   of the internet is Big Endian and the computer may not be.

\emph{ Read a page from a www server }
  --------
   include $<$sys/socket.h$>$
   include $<$stdio.h$>$
   include $<$unistd.h$>$
   include $<$netinet/in.h$>$
   include $<$netdb.h$>$
   include $<$string.h$>$
   //\#include $<$arpa/inet.h$>$
   void getPage(int sock) $\{$
     char buffer[10000];
     size\_t charRead;
     sprintf(buffer, ``GET /\textbackslash n'');
     write(sock, buffer, strlen(buffer));
     while (1) $\{$
       charRead = read(sock, buffer, 10000);
       if (charRead==0) return;
       fwrite(buffer, sizeof(char), charRead, stdout);
     $\}$
   $\}$
   int main() $\{$
     int sock;
     char hostname[100] = ``www.c2.com'';
     struct sockaddr\_in name;
     struct hostent * hostinfo;
     sock = socket(PF\_INET, SOCK\_STREAM, 0);
     name.sin\_family = AF\_INET;
     hostinfo = gethostbyname(hostname);
     if (hostinfo == NULL) $\{$
       printf(``couldnt resolve hostname '\%s''', hostname);
       return(1);
     $\}$ 

     name.sin\_addr = *((struct in\_addr *)hostinfo-$>$h\_addr);
     name.sin\_port = htons(80);
     if (connect(sock, (const struct sockaddr *)\&name, 
       sizeof(struct sockaddr\_in))==-1) $\{$
       perror(``couldnt connect'');
       return 1;
     $\}$
     getPage(sock);
     return 0;
   $\}$

  ,,,,

\section{Sound And Audio}

  Audio files consist of a 'container' format, which is a file
  format containing mainly 'meta' information about the audio
  data present in the file, and a 'codec' which is usually a
  compression or encryption encoding of the audio data.

\subsection{Portaudio}

  Portaudio is used by the Audacity audio editor.

\emph{ Install the portaudio sound library }
\begin{lstlisting}
  sudo apt-get install libportaudio-dev libportaudio-doc
\end{lstlisting}

\emph{ Play a sound file with portaudio and sndfile }
  \begin{lstlisting}
   #include <stdio.h>
   #include <stdlib.h>
   #include <portaudio.h>
   #include <sndfile.h>
   
   #define FRAMES_PER_BUFFER (1024)
   #define PA_SAMPLE_TYPE  paInt16
   typedef short SAMPLE;
   #define BUFFER_LEN  128
   #define MAX_CHANNELS 2
   
   int sndFile_play (const char *infilename) {
     PaStreamParameters outputParameters;
     PaStream *stream;
     PaError err;
     static short data[BUFFER_LEN];
     SNDFILE      *infile;
     SF_INFO     sfinfo;
     sf_count_t  readcount;
     int channels;
     int srate;
   
     err = Pa_Initialize();
   
     if ( !( infile = sf_open( infilename, SFM_READ, &sfinfo ) ) ) {
       printf ("Not able to open input file %s.\n", infilename);
       puts (sf_strerror (NULL));
       return  1;
     }
   
     if ( sfinfo.channels > MAX_CHANNELS ) {
       printf ("Not able to process more than %d channels\n", MAX_CHANNELS);
       return  1;
     }
     /* FILE INFO */
   
     channels = sfinfo.channels; // channels
     printf("number of channels %d\n", sfinfo.channels);
   
     srate = sfinfo.samplerate; 
     printf("sample rate %d\n", sfinfo.samplerate);
   
     outputParameters.device = Pa_GetDefaultOutputDevice();
     outputParameters.channelCount = sfinfo.channels;
     outputParameters.sampleFormat =  PA_SAMPLE_TYPE;
     outputParameters.suggestedLatency = 
       Pa_GetDeviceInfo( outputParameters.device )->defaultLowOutputLatency;
     outputParameters.hostApiSpecificStreamInfo = NULL;
   
     printf("Begin playback.....\n");
     fflush(stdout);
     err = Pa_OpenStream(
       &stream, NULL, &outputParameters, sfinfo.samplerate,
             FRAMES_PER_BUFFER, paClipOff, NULL, NULL );
   
     if( stream ) {
       err = Pa_StartStream( stream );
       printf("Waiting for playback to finish....\n");
       fflush(stdout);
   
       while ((readcount = sf_read_short( infile, data, BUFFER_LEN*sfinfo.channels ))) {
         err = Pa_WriteStream( stream, data, BUFFER_LEN );
       }
   
       err = Pa_CloseStream( stream );
       printf("Done.\n");
       fflush(stdout);
     }
   
     sf_close( infile ); Pa_Terminate();
     return 0;
   }
  \end{lstlisting}

   
\section{Gstreamer}

  Gstreamer is a 'pipeline' based api for playing, editing and 
  analysing media such as audio and video. It is written in c but
  contain bindings for other languages, such as Python. It may well
  be *the* programmatic api for dealing with media.

  Recently (2012) an important new series of gstreamer was release
  (1.x) but the main linux repositories appear to contain the 
  0.10 series.

  http://tordwessman.blogspot.com.au/2012/01/installing-gstreamer-under-linux.html
     how to compile and run a gstreamer application. 

  See gstreamer.org? for a simple helloworld program for 
  gstreamer.

\emph{ Compile a gstreamer c program }
\begin{lstlisting}
  gcc -Wall helloworld.c -o helloworld $(pkg-config --cflags --libs gstreamer-1.0)
\end{lstlisting}

\section{Color In The Terminal}

  Another way to achieve colour in the terminal is with
  ansi escape sequences (?) (is this portable?)

  http://ascii-table.com/ansi-escape-sequences.php
    a detailed list of ansi escapes, including colours

\emph{ A simpler way to print something in color }
  \begin{lstlisting}
   #include <stdio.h>

   #define KNRM  "\x1B[0m"
   #define KRED  "\x1B[31m"
   #define KGRN  "\x1B[32m"
   #define KYEL  "\x1B[33m"
   #define KBLU  "\x1B[34m"
   #define KMAG  "\x1B[35m"
   #define KCYN  "\x1B[36m"
   #define KWHT  "\x1B[37m"
   
   int main() {
     printf(KRED "red\n");
     printf(KGRN "green\n");
     printf(KYEL "yellow\n");
     // below is worse
     printf("%sblue\n", KBLU);
     printf("%smagenta\n", KMAG);
     printf("%scyan\n", KCYN);
     printf("%swhite\n", KWHT);
     // KNRM return colours to the default
     printf("%snormal\n", KNRM);
     return 0;
   }
   
  \end{lstlisting}

\emph{ A macro to print something in red }
  ---------
    include $<$stdio.h$>$
    define RED  ``\textbackslash x1B[31m''
    define RESET  ``\textbackslash x1B[0m''
    define LOG\_RED(X) printf(RED X RESET)
    main() $\{$ LOG\_RED(``This is in Red''); $\}$
  ,,,

\section{Ncurses}

  The 'ncurses' library allows the programmer to use available
  capabilities of the terminal such as positioning the cursor
  on the screen, printing in color, receiving input from the 
  mouse. Ncurses can be seen as an intermediate step between
  terminal programming and windowed applications.

  
\emph{ Install the ncurses development library }
\begin{lstlisting}
  sudo apt-get libncurses5-dev
\end{lstlisting}

\emph{ Compile a program which uses the ncurses library }
\begin{lstlisting}
  gcc program.c -lncurses
\end{lstlisting}

\emph{ Print hello world }
   \begin{lstlisting}
   #include <ncurses.h>
   int main() {
           initscr();        /* Start curses mode   */
           printw("Hello World !!!");    /* Print Hello World  */
           refresh();       /* Print it on to the real screen */
           getch();         /* Wait for user input */
           endwin();        /* End curses mode     */
           return 0;
   }
   \end{lstlisting}


\emph{ Print with colors }
  ---------
  include $<$ncurses.h$>$
  include $<$stdlib.h$>$

  int main(int argc, char *argv[]) $\{$
     initscr();
     if(has\_colors() == FALSE) $\{$
       endwin();
       printf("Your terminal does not support color\textbackslash n");
       exit(1);
     $\}$
     start\_color(); 
     init\_pair(1, COLOR\_RED, COLOR\_BLACK);
     attron(COLOR\_PAIR(1));
     mvwprintw(stdscr, 0, 9, ``\%s'', ``violoa in color...'');
     refresh();
     attroff(COLOR\_PAIR(1));
     getch(); endwin();
  $\}$
  ,,,

\section{Glib}

  Glib is a library of non graphical utility functions and objects
  for the c language which is usually used in conjunction with gtk

\emph{ Concatenate strings using glib }
\begin{lstlisting}
  str = g_strconcat ("fist name ", name, "?", NULL);
\end{lstlisting}
  
\section{Gtk And Windows}

  The gtk api is the preferred manner to create windowed 
  programs using the c programming language.


  \arrayrulecolor{gray}
  \begin{center}
  \begin{tabular}{ |rl| }
    \multicolumn{2}{c}{\textbf{ gtk components }} \\
  \hline

  \texttt{ glib } & Non graphical utility functions (strings etc) \\ 

  \texttt{ pango } & Text and font rendering (international) \\ 

  \texttt{ gdk } & Drawing \\ 

  \texttt{ gdkpixbuf } & Manipulate images \\ 

  \texttt{ atk } & Accessibility \\ 

    \hline
    \end{tabular}
    \end{center}
\emph{ Install gtk+ development on a debian-style system }
\begin{lstlisting}
  sudo apt-get install gnome-devel
\end{lstlisting}

\emph{ Compile a gtk program }
\begin{lstlisting}
  gcc -Wall test.c -o test $(pkg-config --cflags gtk+-2.0) $(pkg-config --libs gtk+-2.0)
\end{lstlisting}

\emph{ Slightly simpler... compile a gtk program }
\begin{lstlisting}
  gcc -Wall test.c -o test $(pkg-config --cflags gtk+-2.0 --libs gtk+-2.0)
\end{lstlisting}

\subsection{Entry Widgets}
  
   The entry widget is a one-line box which allows the user 
   to enter text.

\emph{ A password entry box }
   \begin{lstlisting}
     #include <gtk/gtk.h>

     static void destroy (GtkWidget *window, gpointer data) {
       gtk_main_quit ();
     }

     int main (int argc, char *argv[]) {
       GtkWidget *window, *hbox, *label, *pass;

       gtk_init (&argc, &argv);
       window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
       gtk_window_set_title (GTK_WINDOW (window), "Password?");
       gtk_container_set_border_width (GTK_CONTAINER (window), 10);
       g_signal_connect (G_OBJECT (window), "destroy",
                         G_CALLBACK (destroy), NULL);

       label = gtk_label_new ("Password:");
       // a password entry widget
       pass = gtk_entry_new ();
       gtk_entry_set_visibility (GTK_ENTRY (pass), FALSE);
       gtk_entry_set_invisible_char (GTK_ENTRY (pass), '*');

       hbox = gtk_hbox_new (FALSE, 5);
       gtk_box_pack_start_defaults (GTK_BOX (hbox), label);
       gtk_box_pack_start_defaults (GTK_BOX (hbox), pass);

       gtk_container_add (GTK_CONTAINER (window), hbox);
       gtk_widget_show_all (window);
       gtk_main (); return 0;
     }
 \end{lstlisting}

\subsection{Comboboxes}

\emph{ Add a set of options to a combobox }
  ---------
   
   GList *glist = NULL;
   
   glist = g\_list\_append (glist, ``String 1'');
   glist = g\_list\_append (glist, ``String 2'');
   glist = g\_list\_append (glist, ``String 3'');
   glist = g\_list\_append (glist, ``String 4'');
   gtk\_combo\_set\_popdown\_strings (GTK\_COMBO (combo), glist);
   
  ,,,

\subsection{Filechooser}
   
\emph{ A simple example of using a file chooser button }
  --------
   include $<$gtk/gtk.h$>$

   static void destroy (GtkWidget *window, gpointer data) $\{$
     gtk\_main\_quit ();
   $\}$

   // When a file is selected, display the full path in the GtkLabel 
   static void file\_changed (
     GtkFileChooser *chooser, GtkLabel *label) $\{$
     gchar *file = gtk\_file\_chooser\_get\_filename (
       GTK\_FILE\_CHOOSER (chooser));
     gtk\_label\_set\_text (label, file);
   $\}$

   int main (int argc, char *argv[]) $\{$
     GtkWidget *window, *chooser, *label, *vbox;

     gtk\_init (\&argc, \&argv);
     window = gtk\_window\_new (GTK\_WINDOW\_TOPLEVEL);
     gtk\_window\_set\_title (GTK\_WINDOW (window), ``Simple File Chooser'');
     gtk\_container\_set\_border\_width (GTK\_CONTAINER (window), 10);

     g\_signal\_connect (G\_OBJECT (window), ``destroy'',
                       G\_CALLBACK (destroy), NULL);
     label = gtk\_label\_new ("");
     chooser = gtk\_file\_chooser\_button\_new (
       ``Choose a File'', GTK\_FILE\_CHOOSER\_ACTION\_OPEN);

     g\_signal\_connect (G\_OBJECT (chooser), ``selection\_changed'',
                       G\_CALLBACK (file\_changed),
                       (gpointer) label);

     // Set chooser to the user's home directory.
     gtk\_file\_chooser\_set\_current\_folder (GTK\_FILE\_CHOOSER (chooser), 
                                          g\_get\_home\_dir());

     vbox = gtk\_vbox\_new (FALSE, 5);
     gtk\_box\_pack\_start\_defaults (GTK\_BOX (vbox), chooser);
     gtk\_box\_pack\_start\_defaults (GTK\_BOX (vbox), label);

     gtk\_container\_add (GTK\_CONTAINER (window), vbox);
     gtk\_widget\_show\_all (window);

     gtk\_main ();
     return 0;
   $\}$
 ,,,

\emph{ Use a file chooser with a file filter  }
  --------

   include $<$gtk/gtk.h$>$

   static void destroy (GtkWidget *window, gpointer data) $\{$
     gtk\_main\_quit ();
   $\}$

   // When a file is selected, display the full path in the GtkLabel 
   static void file\_changed (
     GtkFileChooser *chooser, GtkLabel *label) $\{$
     gchar *file = gtk\_file\_chooser\_get\_filename (
       GTK\_FILE\_CHOOSER (chooser));
     gtk\_label\_set\_text (label, file);
   $\}$

   int main (int argc, char *argv[]) $\{$
     GtkWidget *window, *chooser, *label, *vbox;
     GtkFileFilter *filter;

     gtk\_init (\&argc, \&argv);
     window = gtk\_window\_new (GTK\_WINDOW\_TOPLEVEL);
     gtk\_window\_set\_title (GTK\_WINDOW (window), ``File Chooser Button'');
     gtk\_container\_set\_border\_width (GTK\_CONTAINER (window), 10);

     g\_signal\_connect (G\_OBJECT (window), ``destroy'',
                       G\_CALLBACK (destroy), NULL);

     label = gtk\_label\_new ("");
     
     chooser = gtk\_file\_chooser\_button\_new (
       ``Choose a File'', GTK\_FILE\_CHOOSER\_ACTION\_OPEN);

     g\_signal\_connect (G\_OBJECT (chooser), ``selection\_changed'',
                       G\_CALLBACK (file\_changed),
                       (gpointer) label);

     // Set chooser to the user's home directory.
     gtk\_file\_chooser\_set\_current\_folder (GTK\_FILE\_CHOOSER (chooser), 
                                          g\_get\_home\_dir());

     /* a filter to show only 3 types of images. */
     filter = gtk\_file\_filter\_new ();
     gtk\_file\_filter\_set\_name (filter1, ``Image Files'');
     gtk\_file\_filter\_add\_pattern (filter1, ``*.png'');
     gtk\_file\_filter\_add\_pattern (filter1, ``*.jpg'');
     gtk\_file\_filter\_add\_pattern (filter1, ``*.gif'');

     // Add both filters to file chooser button that selects files.
     gtk\_file\_chooser\_add\_filter (GTK\_FILE\_CHOOSER (chooser), filter);

     vbox = gtk\_vbox\_new (FALSE, 5);
     gtk\_box\_pack\_start\_defaults (GTK\_BOX (vbox), chooser);
     gtk\_box\_pack\_start\_defaults (GTK\_BOX (vbox), label);

     gtk\_container\_add (GTK\_CONTAINER (window), vbox);
     gtk\_widget\_show\_all (window);

     gtk\_main ();
     return 0;
   $\}$
 ,,,

\emph{ A folder chooser  }
  --------
   include $<$gtk/gtk.h$>$

   static void folder\_changed (GtkFileChooser*, GtkLabel*);
   static void destroy (GtkWidget *window, gpointer data) $\{$
     gtk\_main\_quit ();
   $\}$

   int main (int argc, char *argv[]) $\{$
     GtkWidget *window, *chooser, *label, *vbox;

     gtk\_init (\&argc, \&argv);
     window = gtk\_window\_new (GTK\_WINDOW\_TOPLEVEL);
     gtk\_window\_set\_title (GTK\_WINDOW (window), ``Folder Chooser'');
     gtk\_container\_set\_border\_width (GTK\_CONTAINER (window), 10);

     g\_signal\_connect (G\_OBJECT (window), ``destroy'',
                       G\_CALLBACK (destroy), NULL);

     label = gtk\_label\_new ("");
     chooser = gtk\_file\_chooser\_button\_new (
       ``Chooser a Folder'', GTK\_FILE\_CHOOSER\_ACTION\_SELECT\_FOLDER);

     /* Monitor when the selected folder or file are changed. */
     g\_signal\_connect (G\_OBJECT (chooser), ``selection\_changed'',
                       G\_CALLBACK (folder\_changed),
                       (gpointer) label);

     // Set chooser buttons to location of the user's home directory.
     gtk\_file\_chooser\_set\_current\_folder (GTK\_FILE\_CHOOSER (chooser), 
                                          g\_get\_home\_dir());

     vbox = gtk\_vbox\_new (FALSE, 5);
     gtk\_box\_pack\_start\_defaults (GTK\_BOX (vbox), chooser);
     gtk\_box\_pack\_start\_defaults (GTK\_BOX (vbox), label);

     gtk\_container\_add (GTK\_CONTAINER (window), vbox);
     gtk\_widget\_show\_all (window);

     gtk\_main ();
     return 0;
   $\}$

   /* display the full path in the GtkLabel widget. */
   static void folder\_changed (
     GtkFileChooser *chooser, GtkLabel *label) $\{$
     gchar *file = gtk\_file\_chooser\_get\_filename (
       GTK\_FILE\_CHOOSER (chooser));
     gtk\_label\_set\_text (label, file);
   $\}$
 ,,,

\subsection{Textview Widget}

  A comprehensive text editor and renderer.
  
\emph{ A simple textview widget in a scrolled window  }
  \begin{lstlisting}
    #include <gtk/gtk.h>

    int main (int argc, char *argv[]) {
      GtkWidget *window, *scrolled_win, *textview;
      GtkTextBuffer *buffer;
      
      gtk_init (&argc, &argv);
      
      window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
      gtk_window_set_title (GTK_WINDOW (window), "Text Views");
      gtk_container_set_border_width (GTK_CONTAINER (window), 10);
      gtk_widget_set_size_request (window, 250, 150);
      
      g_signal_connect (G_OBJECT (window), "destroy",
                        G_CALLBACK (gtk_main_quit), NULL);
      
      textview = gtk_text_view_new ();
      buffer = gtk_text_view_get_buffer (GTK_TEXT_VIEW (textview));
      gtk_text_buffer_set_text(buffer, "A 1st GtkTextView widget!", -1);
      
      scrolled_win = gtk_scrolled_window_new (NULL, NULL);
      gtk_container_add (GTK_CONTAINER (scrolled_win), textview);
      gtk_scrolled_window_set_policy (
        GTK_SCROLLED_WINDOW (scrolled_win),
        GTK_POLICY_AUTOMATIC, GTK_POLICY_ALWAYS);
      gtk_container_add (GTK_CONTAINER (window), scrolled_win);
      gtk_widget_show_all (window);
      gtk_main();
      return 0;
    }
  \end{lstlisting}

\subsection{Images}

  https://developer.gnome.org/gtk3/stable/GtkImage.html
    The official api documentation for GtkImage

\emph{ Insert an image into a textview widget }
  \begin{lstlisting}
    #include <gtk/gtk.h>

    int main (int argc, char *argv[]) {
      GtkWidget *window, *scrolled_win, *textview;
      GdkPixbuf *img;
      GtkTextIter line;
      GtkTextBuffer *buffer;
      
      gtk_init (&argc, &argv);
      
      window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
      gtk_window_set_title (GTK_WINDOW (window), "Pixbuf Images");
      gtk_container_set_border_width (GTK_CONTAINER (window), 10);
      gtk_widget_set_size_request (window, 200, 150);
      
      g_signal_connect (G_OBJECT (window), "destroy",
                        G_CALLBACK (gtk_main_quit), NULL);
      
      textview = gtk_text_view_new ();
      buffer = gtk_text_view_get_buffer (GTK_TEXT_VIEW (textview));
      gtk_text_buffer_set_text (buffer, " Undo\n Redo", -1);

      // Create an image and insert into the text buffer.
      img = gdk_pixbuf_new_from_file (argv[1], NULL);
      gtk_text_buffer_get_iter_at_line (buffer, &line, 0);
      gtk_text_buffer_insert_pixbuf (buffer, &line, img);

      scrolled_win = gtk_scrolled_window_new (NULL, NULL);
      gtk_container_add (GTK_CONTAINER (scrolled_win), textview);
      gtk_container_add (GTK_CONTAINER (window), scrolled_win);
      gtk_widget_show_all (window);

      gtk_main();
      return 0;
    }
  
  \end{lstlisting}

\subsection{Gdkpixbuf}

  The gdkpixbuf is the data/object type used to read, analyse, 
  manipulate and save to file image data within the gtk api.
  It includes functions to crop, rotate, scale, and composite images

  https://developer.gnome.org/gdk-pixbuf/stable/
    the official and good documentation for the gdkpixbuf

\emph{ Some standard supported gdkpixbuf formats are  }
  ``jpeg'', ``png'', ``tiff'', ``ico'' or ``bmp''

  The code below does not print anything, just creates a list of 
  writeable formats.

\emph{ Get a list of all writeable image formats }
  \begin{lstlisting}
   // #include <gdk-pixbuf/gdk-pixbuf.h>
   #include <gtk/gtk.h>

   int main (int argc, char** argv) {

     void add_if_writable (GdkPixbufFormat *data, GSList **list) {
       if (gdk_pixbuf_format_is_writable (data))
         *list = g_slist_prepend (*list, data);
     }
   
     GSList *formats = gdk_pixbuf_get_formats();
     GSList *writable_formats = NULL;
     g_slist_foreach (formats, (GFunc)add_if_writable, &writable_formats);
     g_slist_free (formats);
     return 0;
   }
  \end{lstlisting}

\subsection{Gtkimage Widgets}

  The GtkImage widget is an easy way to add an image to a gtk container
  object. It is a 'higher' level interface than a GdkPixBuf object.

\emph{ Possibly the simplest gtk code for displaying an image }
  \begin{lstlisting}
   #include <gtk/gtk.h>
   void destroy(void) {
     gtk_main_quit();
   }
   
   int main (int argc, char** argv) {
     GtkWidget* window;
     GtkWidget* image;
   
     gtk_init (&argc, &argv);
   
     window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
     image  = gtk_image_new_from_file(argv[1]);
     gtk_signal_connect(GTK_OBJECT (window), "destroy",
                        GTK_SIGNAL_FUNC (destroy), NULL);
   
     gtk_container_add(GTK_CONTAINER (window), image);
     gtk_widget_show_all(window);
     gtk_main();
     return 0;
   }
   
   \end{lstlisting}

\emph{ Can be compiled with }
\begin{lstlisting}
  gcc -Wall img.c -o img `pkg-config --cflags gtk+-2.0` `pkg-config --libs gtk+-2.0`
\end{lstlisting}

\emph{ Load an image from file }
\begin{lstlisting}
  GtkWidget * gtk_image_new_from_file(const gchar * filename);
\end{lstlisting}

\emph{ Creating a new stock image and adding it to a box }
  ----
    image = gtk\_image\_new\_from\_stock(GTK\_STOCK\_DIALOG\_INFO, GTK\_ICON\_SIZE\_DIALOG);
    hbox = gtk\_hbox\_new(FALSE, 5);
    gtk\_box\_pack\_start\_defaults(GTK\_BOX(hbox, image);
    ...
  ,,,

\emph{ Use an image as the background for a widget }
  \begin{lstlisting}

  GdkPixbuf *image = NULL;
  GdkPixmap *background = NULL;
  GtkStyle *style = NULL;

  image = gdk_pixbuf_new_from_file ("background.jpg", NULL);
  gdk_pixbuf_render_pixmap_and_mask (image, &background, NULL, 0);
  style = gtk_style_new ();
  style->bg_pixmap [0] = background;

  gtk_widget_set_style (GTK_WIDGET(widget), GTK_STYLE (style));

  \end{lstlisting}
  
\subsection{Colors With Gtk}

\emph{ Define a new colour }
\begin{lstlisting}
  GdkColor red = {0, 0xffff, 0x0000, 0x0000};
\end{lstlisting}

\emph{ Set the background colour of a gtk widget }
  \begin{lstlisting}
    GdkColor color;
    gdk_color_parse("#00FF7F", &color);
    gtk_widget_modify_bg(widget, GTK_STATE_NORMAL, &color);
  \end{lstlisting}

\emph{ A color chooser button }
  \begin{lstlisting}
    #include <gtk/gtk.h>

    static void color_changed (GtkColorButton*, GtkWidget*);
    static void destroy (GtkWidget *window, gpointer data) {
      gtk_main_quit ();
    }

    int main (int argc, char *argv[]) {
      GtkWidget *window, *button, *label, *hbox;
      GdkColor color;

      gtk_init (&argc, &argv);
      window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
      gtk_window_set_title (GTK_WINDOW (window), "Color Button");
      gtk_container_set_border_width (GTK_CONTAINER (window), 10);

      g_signal_connect (G_OBJECT (window), "destroy",
                        G_CALLBACK (destroy), NULL);

      /* Set initial color as #003366 and set the dialog title. */
      gdk_color_parse ("#003366", &color);
      button = gtk_color_button_new_with_color (&color);
      gtk_color_button_set_title (GTK_COLOR_BUTTON (button),
        "Select a Color");
      
      label = gtk_label_new ("Look at my color!");
      gtk_widget_modify_fg (label, GTK_STATE_NORMAL, &color);
      g_signal_connect (G_OBJECT (button), "color_set",
                        G_CALLBACK (color_changed),
                        (gpointer) label);
      
      hbox = gtk_hbox_new (FALSE, 5);
      gtk_box_pack_start_defaults (GTK_BOX (hbox), button);
      gtk_box_pack_start_defaults (GTK_BOX (hbox), label);

      gtk_container_add (GTK_CONTAINER (window), hbox);
      gtk_widget_show_all (window);
      gtk_main (); return 0;
    }

    /* set selected color as the GtkLabel's foreground color. */
    static void
    color_changed (GtkColorButton *button, GtkWidget *label) {
      GdkColor color;
      gtk_color_button_get_color (button, &color);
      gtk_widget_modify_fg (label, GTK_STATE_NORMAL, &color);
    }
    \end{lstlisting}

\subsection{Layout}

\emph{ Layout a vertical box }
  --------
    include $<$gtk/gtk.h$>$

    static void destroy (GtkWidget*, gpointer);

    define NAMES 4
    const gchar* names[] = $\{$ ``Andrew'', ``Joe'', ``Samantha'', ``Jonathan'' $\}$;

    int main (int argc, 
              char *argv[]) $\{$
      gint i;
      GtkWidget *window, *vbox;
      gtk\_init (\&argc, \&argv);

      window = gtk\_window\_new (GTK\_WINDOW\_TOPLEVEL);
      gtk\_window\_set\_title (GTK\_WINDOW (window), ``Boxes'');
      gtk\_container\_set\_border\_width (GTK\_CONTAINER (window), 10);
      gtk\_widget\_set\_size\_request (window, 150, -1);

      g\_signal\_connect (G\_OBJECT (window), ``destroy'',
                        G\_CALLBACK (destroy), NULL);
      
      vbox = gtk\_vbox\_new (TRUE, 5);
      
      /* Add four buttons to the vertical box. */
      for (i = 0; i $<$ NAMES; i++) $\{$
        GtkWidget *button = gtk\_button\_new\_with\_label (names[i]);
        gtk\_box\_pack\_start\_defaults (GTK\_BOX (vbox), button);
        g\_signal\_connect\_swapped (G\_OBJECT (button), ``clicked'',
                                  G\_CALLBACK (gtk\_widget\_destroy),
                                  (gpointer) button);
      $\}$

      gtk\_container\_add (GTK\_CONTAINER (window), vbox);
      gtk\_widget\_show\_all (window);

      gtk\_main ();
      return 0;
    $\}$

    static void
    destroy (GtkWidget *window,
             gpointer data)
    $\{$
      gtk\_main\_quit ();
    $\}$
   ,,,

\subsection{Gdkpixbuf}

  The 'gdkpixbuf' library allows the viewing and editing 
  of images. It is usually used in conjunction with the gtk
  api.

\emph{ Load an image from a pixbuf }
  --------
     GError * error = NULL; 
     GdkPixbuf * logo = gdk\_pixbuf\_new\_from\_file(``/path/to/logo.png'', \&error);
     GtkWidget * gtk\_image\_new\_from\_pixbuf(logo);
  ,,,
  
\emph{ Scale a GdkPixbuf image }
\begin{lstlisting}
  GdkPixbuf * gdk_pixbuf_scale_simple(const GdkPixbuf * src, int width, int height,
\end{lstlisting}
     GdkInterpType interpolation);

\emph{ Eg }
\begin{lstlisting}
  newpixbuf = gdk_pixbuf_scale_simple(oldpixbuf, 500, 500, GDK_INTERP_BILINEAR);
\end{lstlisting}

\subsection{Events}

  Events are things which happen which are not generated by
  the normal flow of the program. This can include human generated
  events such as mouse-clicks, keyboard presses and releases
  and any other human controlled input device. Events can also
  be generated by other processes or threads performing tasks.
  For example,the termination of loading a large image file into
  memory may generate an event.

  In gtk events emit 'signals'

  Some widgets, (such as the GtkLabel) do not generate events
  and need to be placed into a GtkEventBox if events are required.

\emph{ Use an eventbox to capture click events on a GtkLabel }
  \begin{lstlisting}
   #include <gtk/gtk.h>
   
   static void destroy (GtkWidget *window, gpointer data)
     { gtk_main_quit (); }
   
   static gboolean 
   button_pressed (GtkWidget*, GdkEventButton*, GtkLabel*);
   
   int main (int argc, char *argv[]) {
     GtkWidget *window, *eventbox, *label;
   
     gtk_init (&argc, &argv);
   
     window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
     gtk_window_set_title (GTK_WINDOW (window), "Event Box");
     gtk_container_set_border_width (GTK_CONTAINER (window), 10);
     gtk_widget_set_size_request (window, 200, 50);
   
     g_signal_connect (G_OBJECT (window), "destroy",
                       G_CALLBACK (destroy), NULL);
   
     eventbox = gtk_event_box_new ();
     label = gtk_label_new ("Double-Click Me!");
   
     // Set order for receiving notification of events. 
     gtk_event_box_set_above_child (GTK_EVENT_BOX (eventbox), FALSE);
   
     g_signal_connect (G_OBJECT (eventbox), "button_press_event",
                       G_CALLBACK (button_pressed), (gpointer) label);
   
     gtk_container_add (GTK_CONTAINER (eventbox), label);
     gtk_container_add (GTK_CONTAINER (window), eventbox);
   
     /* the event box catches button presses, set the
      * cursor to hand when the mouse is over the event box. */
     gtk_widget_set_events (eventbox, GDK_BUTTON_PRESS_MASK);
     gtk_widget_realize(eventbox);
     gdk_window_set_cursor(eventbox->window, gdk_cursor_new (GDK_HAND1));
     gtk_widget_show_all (window);
     gtk_main (); return 0;
   }
   
   // called every time a button-press occurs on the GtkEventBox. 
   static gboolean
   button_pressed (GtkWidget *eventbox,
                   GdkEventButton *event,
                   GtkLabel *label) {
     if (event->type == GDK_2BUTTON_PRESS) {
       const gchar *text = gtk_label_get_text (label);
       if (text[0] == 'D')
         gtk_label_set_text (label, "I Was Double-Clicked!");
       else
         gtk_label_set_text (label, "Double-Click Me Again!");
     }
     return FALSE;
   }
  \end{lstlisting}

\subsection{Keypress Events In Gtk}

  Return FALSE from the ``key\_press'' event handler to allow the 
  widget to handle the event normally.

\emph{ Testing keypresses  }
  \begin{lstlisting}
    #include <gtk/gtk.h>

    static gboolean keyPressed (GtkEntry * entry, GdkEventKey * event) {
      guint k = event->keyval;
      gint value = g_ascii_digit_value (event->string[0]);
      return FALSE;
    }
    static void destroy (GtkWidget *window, gpointer data) {
      gtk_main_quit ();
    }

    int main (int argc, char *argv[]) {
      GtkWidget *window, *entry, *label, *hbox;
      GdkColor color;

      gtk_init (&argc, &argv);
      window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
      gtk_window_set_title (GTK_WINDOW (window), "Key presses");
      gtk_container_set_border_width (GTK_CONTAINER (window), 10);

      g_signal_connect (G_OBJECT (window), "destroy",
                        G_CALLBACK (destroy), NULL);
      
      label = gtk_label_new ("key press");
      entry = gtk_entry_new ();
      
      g_signal_connect (G_OBJECT(entry), "key-press-event",
                    G_CALLBACK (keyPressed), NULL);
      
      hbox = gtk_hbox_new (FALSE, 5);
      gtk_box_pack_start_defaults (GTK_BOX (hbox), label);
      gtk_box_pack_start_defaults (GTK_BOX (hbox), entry);

      gtk_container_add (GTK_CONTAINER (window), hbox);
      gtk_widget_show_all (window);
      gtk_main (); return 0;
    }
    \end{lstlisting}

\section{The Gnu C Compiler}


  \arrayrulecolor{gray}
  \begin{center}
  \begin{tabular}{ |rl| }
    \multicolumn{2}{c}{\textbf{ header file search folders }} \\
  \hline

   \texttt{ /usr/local/include } & \\ 

   \texttt{ libdir/gcc/target/version/include } & \\ 

   \texttt{ /usr/target/include } & \\ 

   \texttt{ /usr/include } & \\ 

    \hline
    \end{tabular}
    \end{center}
\emph{ Add to the header include folders }
\begin{lstlisting}
  gcc -Idir
\end{lstlisting}

\emph{ Add folders for quoted included header file eg: \#include ``header.h'' }
\begin{lstlisting}
  gcc -iquote folder
\end{lstlisting}

\emph{ Create object files f1.o and f2.o }
\begin{lstlisting}
  gcc -c f1.c f1.c
\end{lstlisting}

\emph{ Create an executable file from object file linking the math library }
\begin{lstlisting}
  gcc function.o test.o -o test -lm  ~(this links 'lib/libm.a')
\end{lstlisting}

\emph{ Link a library 'libtest.a'  in the current folder }
\begin{lstlisting}
  gcc prog.o -L. -ltest
\end{lstlisting}

\emph{ Create an executable called 'test' from test.c and the function 'func.c' }
\begin{lstlisting}
  gcc func.c test.c -o test
\end{lstlisting}

\emph{ Create an archive (library) }
\begin{lstlisting}
  ar cr ....
\end{lstlisting}

\subsection{Using Make To Compile Programs}

  The principle behind make is to only compile code if it, or one of its
  dependencies has been modified. This saves time with large
  projects.

\emph{ A very simple makefile called 'Makefile' }
  \begin{lstlisting}
    test: test.o ffunction.o
       gcc ffunction.o test.o -o test
    test.o: test.c
       gcc -c test.c
    ffunction.o: ffunction.c
       gcc -c ffunction.c
    clean:
      rm *.o
   \end{lstlisting}

   (the command lines have to begin with a tab)

\emph{ Only execute compile 'test' if 'test.o' or 'f1.o' has changed }
  \begin{lstlisting}
    test: test.o f1.o
       gcc f1.o test.o -o test
  \end{lstlisting}

\emph{ Run only the rule 'clean' from a makefile }
\begin{lstlisting}
  make clean
\end{lstlisting}

\emph{ Compile a program with a make file }
\begin{lstlisting}
  make
\end{lstlisting}

\subsection{Making Static Libraries}
   
  ``ar'': $<$ar$>$chive c code files

  \begin{itemize}
  \item  it is a convention that static library files are named
     with a '.a' extention
   \item  libraries make it easier to distribute code since only one
     file has to be installed
\end{itemize}
\emph{ Show the contents (files in) of the library 'somelibrary.a' }
\begin{lstlisting}
  ar t somelibrary.a
\end{lstlisting}
\begin{lstlisting}
  ar tv somelibrary.a ~(the same but more verbose output)
\end{lstlisting}

\emph{ Create or update a library file 'somelibrary.a' with 3 files  }
\begin{lstlisting}
  ar r somelibrary.a functionA.o functionB.o functionC.o
\end{lstlisting}

\emph{ Add a file to a library file }
\begin{lstlisting}
  ar q library.a functionA.o
\end{lstlisting}

\emph{ Extract files from a library archive }
\begin{lstlisting}
  ar x somelibrary.a
\end{lstlisting}

\emph{ Use a library to create an executable file called 'test' }
\begin{lstlisting}
  gcc test.c somelibrary.a -o test
\end{lstlisting}

\emph{ A makefile to build a static library }
   \begin{lstlisting}
    library.a: functionA.o functionB.o
      ar rv libsome.a functionA.o functionB.o
      rm functionA.o functionB.o
   \end{lstlisting}

\emph{ Add a table of contents to an archive file }
\begin{lstlisting}
  ar s libsome.a
\end{lstlisting}

   (this can be run with 'make'. or 'make clean' to remove .o files)
   
\emph{ Use a make file which is called 'create' not 'Makefile' }
\begin{lstlisting}
  make -f create 
\end{lstlisting}

\subsection{Shared Libraries}

  Shared libraries have names like 'libc.so.6' and are loaded
  dynamically when a program is run, instead of being compiled into
  the executable binary of a program, as is the case of static libraries
  made with the 'ar' program.

\emph{ Check what shared libraries the program 'wc' needs to run }
\begin{lstlisting}
  ldd /usr/bin/wc
\end{lstlisting}

\subsection{Gcc Error Messages Decifered}

  $>$ 'segmentation fault'
    This means that you are trying to access memory which you
    shouldnt be accessing. An array out-of-bounds, past the end of 
    a string etc etc.

\emph{ An undefined type or variable in a header file function declaration }
\begin{lstlisting}
  error: expected ‘)’ before ‘*’ token
\end{lstlisting}

  error message: 
    file.c:6: error: conflicting types for ‘aFunction’
    header.h:49: error: previous declaration of ‘aFunction’ was here
  explanation:

\section{Books}

\begin{description}[labelindent=1cm, leftmargin=2cm, style=nextline]
 \item[\url{C}] in a nutshell (O'Reilly)
     An excellent and comprehensive book
\end{description}

\section{Links}
  
   http://library.gnome.org/devel/gtk-tutorial/stable/
     a gtk tutorial

\section{Knowledgeable People}

  Chas Owens (stack overflow) about images

\section{Vim And C}

  The vim editor can be used to write c programs and program
  fragments. These programs and fragments can be compiled and
  run from within the vim editor- a kind of basic 'ide' or 
  integrated development environment.
 
  The following vim commands and maps can be placed 
  inside the 'vimrc' file, which is the configuration file
  for vim and is usually located at /etc/vim/vimrc or
  $\sim$/.vimrc

\emph{ Compile the current file with gcc  }
\begin{lstlisting}
  map ,gcc :!gcc %<cr>
\end{lstlisting}

\emph{ Compile the current c file with tcc minimalist c compiler }
\begin{lstlisting}
  map ,tcc :!tcc %<cr>
\end{lstlisting}
 
\emph{ A vim map to compile and run a 'c' program between '---' and ',,,' }
\begin{lstlisting}
  map ,scc :?^ *---?+1,/^ *,,,/-1w! test.c \| !gcc test.c; ./a.out<cr>
\end{lstlisting}

\emph{ A more complicated map which compiles with gtk if necessary }
\begin{lstlisting}
  map ,gtk :?^ *---?+1,/^ *,,,/-1w! fragment.c \| !n=$(grep -c gtk.h fragment.c); if [ $n -gt 0 ]; then gcc -Wall fragment.c  $(pkg-config --cflags gtk+-2.0 --libs gtk+-2.0); else gcc -Wall fragment.c; fi
\end{lstlisting}

\emph{ Compile \& run a c fragment add skeleton code !!bug '\#' }
\begin{lstlisting}
  map ,fcc :?^ *---?+1,/,,,/-1w ! (echo -e '#include <stdio.h> \n int main () \n{' ; sed 's/a/a/'; echo -e '  }\n}') > fragment.c; gcc fragment.c; ./a.out 
\end{lstlisting}

\emph{ Compile \& run a c program within --- and ,,, }
\begin{lstlisting}
  map ,fcc :?^ *---?+1,/,,,/-1w ! ( cat - ) > fragment.c; gcc fragment.c; ./a.out 
\end{lstlisting}

 The astyle c formatting utility can be used in conjunction with
 the vim editor to format and indent an entire c file or ooly
 a part of the file.

\emph{ Install the 'astyle' formatting program }
\begin{lstlisting}
  sudo apt-get install astyle
\end{lstlisting}

  The vim 'maps' below can be placed in the vimrc file 
  (often located at $\sim$/.vimrc) so that they will always be 
  available when vim is started.
  
\emph{ Indent a the whole c file with astyle }
\begin{lstlisting}
  map ,ii :%! astyle -s2 <cr>
\end{lstlisting}

\emph{ Indent text between --- and ,,, with astyle }
\begin{lstlisting}
  map ,ci :?^ *---?+1,/^ *,,,/-1! astyle -s2 <bar> sed 's/^/   /'<cr>
\end{lstlisting}
 
  The map above is invoked by typing ',ci' when the vim editor is
  in 'normal' mode (that is not insert mode etc). It is designed to
  format code which is embedded in a normal text document. This 
  is mainly useful when writing about c programs.

\emph{ Indent a the whole c file with astyle breaking open braces }
\begin{lstlisting}
  map ,ii :%! astyle -bs2 <cr>
\end{lstlisting}

   \end{document}
