Author Topic: C Lessons  (Read 10201 times)

0 Members and 1 Guest are viewing this topic.

Charles Pegge

  • Admin Support Member
  • *****
  • Posts: 4315
    • Oxygen Basic
C Lessons
« on: August 10, 2011, 07:40:13 AM »
I'm taking some time out to study C with a view to making tools for cross platform devlopment. I was surprised to find that GCC works without any switches. I have MinGW installed, and all it needs is:

bin\gcc prog.c

and voila! It compiles to a.exe by default

Here is my crash course so far. C material is very easy to find on the web.


C Source 1
Code: (c) [Select]
 int main()
  {
    return 0;
  };

C Source 2
Code: (c) [Select]
 #include <stdio.h>

  int main()
  {
    // int a;
    printf ("Hello World!\n");
    return 0;
  };

C Source 3
Code: (c) [Select]

  /* malloc example: string generator*/

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

  int main ()
  {
  int i,n;
  char * buffer;

  printf ("How long do you want the string? ");
  scanf ("%d", &i);

  buffer = (char*) malloc (i+1);
  if (buffer==NULL) exit (1);

  for (n=0; n<i; n++)
    buffer[n]=rand()%26+'a';
  buffer[i]='\0';

  printf ("Random string: %s\n",buffer);
  free (buffer);

  return 0;
  };

C Source 4
Code: (c) [Select]
 // http://www.cplusplus.com/reference/clibrary/cstdio/scanf/

  /* scanf example */
  #include <stdio.h>

  int main ()
  {
  char str [80];
  int i;

  printf ("Enter your family name: ");
  scanf ("%s",str);  
  printf ("Enter your age: ");
  scanf ("%d",&i);
  printf ("Mr. %s , %d years old.\n",str,i);
  printf ("Enter a hexadecimal number: ");
  scanf ("%x",&i);
  printf ("You have entered %#x (%d).\n",i,i);
  
  return 0;
  }


C Source 5
Code: (c) [Select]
 // http://www.cplusplus.com/reference/clibrary/cstdio/fopen/

  /* fopen example */
  #include <stdio.h>
  int main ()
  {
  FILE * pFile;
  pFile = fopen ("myfile.txt","w");
  if (pFile!=NULL)
  {
    fputs ("fopen example",pFile);
    fclose (pFile);
  }
  return 0;
 }

C Source 6
Code: (c) [Select]
 // http://www.cplusplus.com/reference/clibrary/cstdio/setbuf/

  /* setbuf example */
  #include <stdio.h>

  int main ()
  {
  char buffer[BUFSIZ];
  FILE *pFile1, *pFile2;

  pFile1=fopen ("myfile.txt","w");
  pFile2=fopen ("myfile2.txt","a");

  setbuf ( pFile1 , buffer );
  fputs ("This is sent to a buffered stream",pFile1);
  fflush (pFile1);

  setbuf ( pFile2 , NULL );
  fputs ("This is sent to an unbuffered stream",pFile2);

  fclose (pFile1);
  fclose (pFile2);

  return 0;
  }

C Source 7
Code: (c) [Select]
 // http://www.cplusplus.com/reference/clibrary/cstdio/fread/

/* fread example: read a complete file */
#include <stdio.h>
#include <stdlib.h>

int main () {
  FILE * pFile;
  long lSize;
  char * buffer;
  size_t result;

  pFile = fopen ( "myfile.bin" , "rb" );
  if (pFile==NULL) {fputs ("File error",stderr); exit (1);}

  // obtain file size:
  fseek (pFile , 0 , SEEK_END);
  lSize = ftell (pFile);
  rewind (pFile);

  // allocate memory to contain the whole file:
  buffer = (char*) malloc (sizeof(char)*lSize);
  if (buffer == NULL) {fputs ("Memory error",stderr); exit (2);}

  // copy the file into the buffer:
  result = fread (buffer,1,lSize,pFile);
  if (result != lSize) {fputs ("Reading error",stderr); exit (3);}

  /* the whole file is now loaded in the memory buffer. */

  // terminate
  fclose (pFile);
  free (buffer);
  return 0;
}

C Source 8
Code: (c) [Select]
 // http://www.cplusplus.com/reference/clibrary/cstdio/fseek/

  /* fseek example */
  #include <stdio.h>

  int main ()
  {
  FILE * pFile;
  pFile = fopen ( "example.txt" , "w" );
  fputs ( "This is an apple." , pFile );
  fseek ( pFile , 9 , SEEK_SET );
  fputs ( " sam" , pFile );
  fclose ( pFile );
  return 0;
  }

C Source 9
Code: (c) [Select]
 // http://www.cplusplus.com/reference/clibrary/cstdio/fgets/

/* fgets example */
#include <stdio.h>

int main()
{
   FILE * pFile;
   char mystring [100];

   pFile = fopen ("myfile.txt" , "r");
   if (pFile == NULL) perror ("Error opening file");
   else {
     fgets (mystring , 100 , pFile);
     puts (mystring);
     fclose (pFile);
   }
   return 0;
}


Charles
« Last Edit: August 11, 2011, 10:22:07 AM by Charles Pegge »

Peter

  • Full Member
  • ***
  • Posts: 161
Re: C Lessons
« Reply #1 on: August 10, 2011, 07:49:34 AM »
cool Charles,

grandmother's C  is alive !

efgee

  • Full Member
  • ***
  • Posts: 172
Re: C Lessons
« Reply #2 on: August 10, 2011, 09:25:33 AM »
Charles,
does this:

Quote
Code: (o2)

mean that these programs can be compiled with oxygen as well?


Charles Pegge

  • Admin Support Member
  • *****
  • Posts: 4315
    • Oxygen Basic
Re: C Lessons
« Reply #3 on: August 10, 2011, 09:38:13 AM »
No, it's just a convenient code format. We don't have the standard C libraries but the syntax would be very close.

Charles


jcfuller

  • Full Member
  • ***
  • Posts: 181
Re: C Lessons
« Reply #4 on: August 10, 2011, 10:42:22 AM »
Charles,
As O2 does classes  might I  suggest that you study up on c++ too (g++) .

James

Charles Pegge

  • Admin Support Member
  • *****
  • Posts: 4315
    • Oxygen Basic
Re: C Lessons
« Reply #5 on: August 10, 2011, 10:52:02 AM »
Certainly James,

C++ is a closer fit and gcc will do both. (In fact gcc will also do Java, Ada and  Fortran!)

Charles
« Last Edit: August 10, 2011, 10:57:07 AM by Charles Pegge »

Peter

  • Full Member
  • ***
  • Posts: 161
Re: C Lessons
« Reply #6 on: August 10, 2011, 03:31:28 PM »
Hi Charles,

another c-lesson  'DiskFree'

Code: [Select]
#include <windows.h>
#include <stdio.h>

int main(void)
{
 long long BytesAvailable,TotalBytesAvailable=0;
 long long capacity,TotalCapacity=0;
 long long userFree,TotalUserFree=0;
 long long used,TotalUsed=0;
 long double percent;
 int counter = 'C';
 char diskname[512];
 strcpy(diskname,"C:\\");
 printf("%-6s %15s %15s %15s %6s\n","Drive", "Capacity",
 "Available","Used","Free");

 while (counter != (1+'Z'))
 {
  diskname[0] = counter;
  if (GetDiskFreeSpaceEx(diskname, &BytesAvailable,
  &capacity,&userFree))
  {
   percent = 100.0L*(((long double)BytesAvailable)/(long
   double)capacity);
   used = capacity-BytesAvailable;
   printf("%-6s %15'lld %15'lld %15'lld %6.2Lf%%\n",
   diskname,capacity,BytesAvailable,used,percent);
   TotalBytesAvailable+=BytesAvailable;
   TotalCapacity+=capacity;
   TotalUsed+=used;
  }
  counter++;
 }

// Now print the totals
percent = 100.0L*(((long double)TotalBytesAvailable)/(long
double)TotalCapacity);
printf("\n%-6s %15'lld %15'lld %15'lld %6.2Lf%%\n", "Total:",
TotalCapacity,TotalBytesAvailable,TotalUsed,percent);
return 0;
}

John

  • Hero Member
  • *****
  • Posts: 3646
Re: C Lessons
« Reply #7 on: August 10, 2011, 03:51:28 PM »
What language was used to write the C language?  (ASM, itself, ...)

Peter

  • Full Member
  • ***
  • Posts: 161
Re: C Lessons
« Reply #8 on: August 11, 2011, 02:59:09 AM »
Hi,

The C programming language was devised in the early 1970s as a system
implementation language for the nascent Unix operating system. Derived
from the typeless language BCPL, it evolved a type structure; created
on a tiny machine as a tool to improve a meager programming
environment, it has become one of the dominant languages of today.

Charles Pegge

  • Admin Support Member
  • *****
  • Posts: 4315
    • Oxygen Basic
Re: C Lessons
« Reply #9 on: August 11, 2011, 04:42:31 AM »

'C' was developed from 'B' but there was no 'A'. :)

Interesting how structs arrived so late in the language.

http://en.wikipedia.org/wiki/C_%28programming_language%29

Charles

Charles Pegge

  • Admin Support Member
  • *****
  • Posts: 4315
    • Oxygen Basic
Re: C Lessons
« Reply #10 on: August 13, 2011, 06:01:09 AM »

Thanks for the DiskFree code Peter.

Function Pointer
Code: (c) [Select]


  // FUNCTION POINTER

  #include <stdio.h>

  int foo(int i,int j)
  {
    printf ("Result %i \n",i+j);
  }

  int (*pfoo)(int i,int j);


  int main()
  {
    pfoo=&foo;
    return pfoo(1,2);
  }

Charles

Peter

  • Full Member
  • ***
  • Posts: 161
Re: C Lessons
« Reply #11 on: August 13, 2011, 07:28:24 AM »
more pointer   :D

Code: [Select]
#include <stdio.h>

int main()
{
 int i;
 int *p;
 
 i =1;
 p =&i;
 
 printf("\nafter p = &i; is\n");
 printf(" i = %d\n",  i);
 printf(" p = %d\n",  p);
 printf("*p = %d\n", *p);
 
 *p = 2;
 
 printf("\nafter *p = 2; is\n");
 printf(" i = %d\n",  i);
 printf(" p = %d\n",  p);
 printf("*p = %d\n", *p);
 
 printf("\nsizeof(int *) = %d\n", sizeof(int *));
 
 getchar();
 return 0;
}
« Last Edit: August 13, 2011, 07:49:31 AM by peter »

Peter

  • Full Member
  • ***
  • Posts: 161
Re: C Lessons
« Reply #12 on: August 13, 2011, 07:50:35 AM »
pointer and malloc
Code: [Select]
#include <stdio.h>
#include <stdlib.h>

int main()
{
 int *p;
 int n =10;
 int i;

 p = (int *) malloc(n * sizeof(int));
 if (!p)
 {
  printf("Error, not enough memory.\n);
  getchar();
  return 0;
 }

 for (i =0; i<10; i++)
  p[i] = 2*i;
 for (i =0; i<10; i++)
  printf("i = %d   p[%d] = %d\n", i, i, p[i]);
 free(p);
 
 getchar();
 return 0;
}


Peter

  • Full Member
  • ***
  • Posts: 161
Re: C Lessons
« Reply #13 on: August 13, 2011, 08:24:01 AM »
more c- lesson sinus.

Code: [Select]
#include <windows.h>
#include <stdio.h>
#include <math.h>

char text[1000];
int imax, jmax;
const double pi = 3.14159265358979323846;
double frequenz = 1.0;
int n = 100;


void Draw(HDC hdc)
{
  double x, y, dx, xmin, xmax, ymin, ymax;
  double xfaktor, yfaktor;
  int i, j, i0, j0;
 
  xmin = 0;
  xmax = 2*pi*frequenz;
  ymin = -1;
  ymax = +1;
 
  // Intervall
  dx = (xmax - xmin)/n;
 
  // Zoomfaktor
  xfaktor = imax/(xmax-xmin);
  yfaktor = jmax/(ymax-ymin);
 
  // move
  i0 = 0;
  j0 = jmax/2;
 
  MoveToEx(hdc, i0, j0, 0);
  for (x = xmin; x <= xmax + dx/2; x += dx) {
   
    // Funktion
    y = sin(x);
   
    // Pixel
    i = i0 + xfaktor * x;
    j = j0 - yfaktor * y;
   
    // lines/boxes
    LineTo(hdc, i, j);
    Rectangle(hdc, i-2, j-2, i+3, j+3);
  }
}

LRESULT CALLBACK WindowProc(HWND hwnd, UINT m, WPARAM wParam, LPARAM lParam)
{
  HDC hdc;
 
  if (m == WM_KEYDOWN) {
    if (wParam == VK_UP    && n < 5000)        n = 3*n/2;
    if (wParam == VK_DOWN  && n > 2)           n = 2*n/3;
    if (wParam == VK_LEFT  && frequenz < 1024) frequenz *= 2;
    if (wParam == VK_RIGHT && frequenz > 0.25) frequenz /= 2;
    InvalidateRect(hwnd, 0, 0);
  }
 
  else if (m == WM_PAINT) {
    hdc = GetDC(hwnd);
    Rectangle(hdc, -1, -1, imax+1, jmax+1);
    Draw(hdc);
    ReleaseDC(hwnd, hdc);
    ValidateRect(hwnd, 0);
    sprintf(text, "Sinus:  f = %.2f  n = %d", frequenz, n);
    SetWindowText(hwnd, text);
  }
 
  else if (m == WM_SIZE) {
    imax = LOWORD(lParam);
    jmax = HIWORD(lParam);
  }
  else if (m == WM_DESTROY)
    PostQuitMessage(0);
  else
    return DefWindowProc(hwnd, m, wParam, lParam);
  return 0;
}


Peter

  • Full Member
  • ***
  • Posts: 161
Re: C Lessons
« Reply #14 on: August 13, 2011, 09:14:49 AM »
lesson pow/sqrt

Code: [Select]
include "window.h"

Def Lila 0xFFC8C8

Window "Quadratic Color 2011",640,480,ws_overlapped
SetFont 16,32,0,0

single x y ax ay tx ty

While WinExit=0
For x=8 To 16
For y=1 To 420
ax= pow(x,2)
ay= pow(y,2)
tx = sqr(ax+ay)
ty = sqr(ax+ay)
Text "PETER",tx,ty,Rgb (Rand(32,255), Rand(32,255), Rand(32,255))
Next: Next
DoEvents
Wend
WinEnd

[attachment deleted by admin]