Oxygen Basic

Information => Reference => Topic started by: Charles Pegge on August 10, 2011, 07:40:13 AM

Title: C Lessons
Post by: Charles Pegge 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
Title: Re: C Lessons
Post by: Peter on August 10, 2011, 07:49:34 AM
cool Charles,

grandmother's C  is alive !
Title: Re: C Lessons
Post by: efgee 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?

Title: Re: C Lessons
Post by: Charles Pegge 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

Title: Re: C Lessons
Post by: jcfuller 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
Title: Re: C Lessons
Post by: Charles Pegge 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
Title: Re: C Lessons
Post by: Peter 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;
}
Title: Re: C Lessons
Post by: John on August 10, 2011, 03:51:28 PM
What language was used to write the C language?  (ASM, itself, ...)
Title: Re: C Lessons
Post by: Peter 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.
Title: Re: C Lessons
Post by: Charles Pegge 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
Title: Re: C Lessons
Post by: Charles Pegge 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
Title: Re: C Lessons
Post by: Peter 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;
}
Title: Re: C Lessons
Post by: Peter 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;
}

Title: Re: C Lessons
Post by: Peter 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;
}

Title: Re: C Lessons
Post by: Peter 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]
Title: Re: C Lessons
Post by: Charles Pegge on August 13, 2011, 09:17:09 AM

Thanks Peter,
I see you have to cast the p pointer when using with malloc.

Charles
Title: Re: C Lessons
Post by: John on August 13, 2011, 11:59:48 PM
It would be nice if a C compiler could deal with type at time of use like SB does. Declaring variables and casting is a PITA. I won't even get started on having to DIM arrays. (PITA-2)  :P


Title: Re: C Lessons
Post by: Charles Pegge on August 14, 2011, 12:35:15 AM

You can do this to some extent in C with macros, pointers and casting. Performance and flexibility are a tradeoff.

Charles
Title: Re: C Lessons
Post by: John on August 14, 2011, 12:46:10 AM
I really think you have to look at the application as a whole. There will be parts that most of the time the application is idle and there are parts that would benefit from a call to an extension module function written in C.

Title: Re: C Lessons
Post by: Charles Pegge on August 30, 2011, 09:03:12 PM

Bstrings and some BASIC string functions for C

Code: (c) [Select]


//=================
//Bstring Functions
//=================


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

  typedef char * bstring;



//------------------------
  bstring NewString(int n)
//========================
  {
  int *p;
  p = (int*) malloc (n+6);
  *p = n;
  p++;
  return (char*) p;
  }



//------------------
  int Len(bstring s)
//==================
  {
  int * p=(int*) s;
  p--;
  return *p;
  }



//----------------------------------------
  void FillString(bstring s, int n, int c)
//========================================
  {
  int i;
  for (i=0 ; i<n ; i++)
  {
  *s = (char) c;
  s++;
  }
  }



//-------------------------
  bstring NullString(int n)
//=========================
  {
  int *p;
  p = (int*) malloc (n+6);
  *p = n;
  p++;
  FillString((bstring) p,n+2,0);
  return (bstring) p;
  }




//-------------------------
  int FreeString(bstring s)
//=========================
  {
  free(s-4);
  return 0;
  }




//------------------------------------
  bstring Mid(bstring s, int i, int l)
//====================================
  {
  bstring t;
  bstring u;
  int le;
  int les=Len(s);
  int j;
  if (i<0)
  {
    i=les+1+i; //offset from the right
  }
  le=l+i-1;
  if (le>les)
  {
   l=les-i+1;
  }
  if (l<0) l=0;
  t=NullString(l);
  if (i>les) return t;
  u=t;
  s+=i-1;
  for (j=0 ; j<=l ; j++) // includes boundary null
  {
    *u++ = *s++;
  }
  return t;
  }



//------------------------------
  bstring Left(bstring s, int i)
//==============================
  {
  return Mid(s,1,i);
  }



//-------------------------------
  bstring Right(bstring s, int i)
//===============================
  {
  return Mid(s,-i,Len(s));
  }




//------------------
  bstring Chr(int i)
//==================
  {
  bstring s=NewString(1);
  *s=(char) i;
  s[1]=(char) 0;
  return s;
 
  }




//--------------------------
  short Asc(bstring s,int i)
//==========================
  {
  long le=Len(s);
  if (i<0)
  {
   i=le+i+1; //offset from the right
  }
  if (i<1) return 0;
  if (i>le) return 0;
  i--;
  return (short) s[i] & 0xff;
 
  }   



//-----------
  int main ()
//===========
  {
  int i,n;
  bstring s,t;

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

  s=NullString(i);
  t=NullString(i);
  if (s==NULL) exit (1);

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

  t=Mid(s,-2,64);
  printf ("Random string: %s, %s, %i, %s \n",s, t, Asc(t,2), Chr(65) );
  FreeString (s);
  FreeString (t);


  return 0;
  };


Charles
Title: Re: C Lessons
Post by: Peter on August 31, 2011, 02:42:15 AM
Hi Charles,

I think the people are visiting this forum, because they are thinking that is a  Basic Forum.
And now they get a shock, if they see is much  stone age C here. It does not matter to me, I am crazy enough to write in all..
I think it will become  more and more Linux than Basic ? 

Some OxygenBasic  examples would be good  to this forum. You can get the feeling,  yes  I am here right. 
Title: Re: C Lessons
Post by: Charles Pegge on August 31, 2011, 08:21:14 AM

Hi Peter,

This dinosaur porridge will eventually become part of my Trans-platform resources. :) and it helps me appraise the possibility of a C emitter.

However I have some more Opengl geometry in the pipeline, based on the Platonic solids and their variations. I hope these will be easier to relate to.

Charles
Title: Re: C Lessons
Post by: John on August 31, 2011, 08:35:14 AM
I think C is the foundation of most OS and development tools we use today. Everything is a derivative of C IMHO. Linux is the future as MS waffles along trying to capture market share and caring less what effect if has on their developer base.

If this forum turns into a thinBasic like venue, then we have a problem. Only 10% of the posts there have anything to do with Basic.
Title: Re: C Lessons
Post by: Peter on August 31, 2011, 09:20:29 AM
Only 10% of the posts there have anything to do with Basic.

yes, that is correct, is more for the hobby social philosopher.  :D
Title: Re: C Lessons
Post by: Peter on August 31, 2011, 09:45:52 AM
did you know, if you learn Java, then can you talk with the Aliens!   :D
Title: Re: C Lessons
Post by: efgee on August 31, 2011, 11:01:11 AM
I really welcome Charles' exploration in C as I like to use/learn as much as I can.
(every programming language is welcome...)
This is because I haven't found THE perfect language yet.
Title: Re: C Lessons
Post by: Aurel on August 31, 2011, 11:24:06 AM
Code: [Select]
did you know, if you learn Java, then can you talk with the Aliens! :D :D :D
But hey maby you wrong - you know my uffo basicers code - it's infact some sort
of Alien language ,man.... :D :D :D

And yes ,this time i 100% agree with Pan  ;)
I know that knowlege about C is usefull ...but
And heh ...yes John is right to about thinF - to much dan babeling about
lisp and derivatives... :-\
Title: Re: C Lessons
Post by: Charles Pegge on August 03, 2012, 08:02:10 AM
GCC Windows (MinGW), Late binding, Midi Output (Tune with 2 notes :))

Code: (c) [Select]

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <windows.h>


int main()
{
  HANDLE li,ha;
  li=LoadLibrary("Winmm.dll");
  //
  int WINAPI (*midiOutOpen)(HANDLE*h,UINT,DWORD_PTR,DWORD_PTR,DWORD);
  midiOutOpen=GetProcAddress(li,"midiOutOpen");
  //
  int WINAPI (*midiOutClose)(HANDLE);
  midiOutClose=GetProcAddress(li,"midiOutClose");
  //
  int WINAPI (*midiOutShortMsg)(HMIDIOUT,DWORD);
  midiOutShortMsg=GetProcAddress(li,"midiOutShortMsg");
  //
  //FARPROC CALLBACK
  HANDLE        hmo;
  int           er;
  long          ch;
  long long     qu1,qu2,fr;
  //
  QueryPerformanceCounter( (LARGE_INTEGER*) &qu1);
  QueryPerformanceFrequency((LARGE_INTEGER*) &fr);
  fr/=1000; // for milliseconds
  //
  er=midiOutOpen(&hmo,0,0,0,0);
  midiOutShortMsg(hmo,0x000EC2); // instrument assign ch
  midiOutShortMsg(hmo,0x503791); // v n (n on)  ch
  Sleep(250);
  midiOutShortMsg(hmo,0x503781); // v n (n off) ch
  midiOutShortMsg(hmo,0x503191); // v n (n on)  ch
  Sleep(3500);
  midiOutShortMsg(hmo,0x503081); // v n (n off) ch
  //
  //MessageBox(0,"Hello","Greeting",0);
  //
  //scanf("%c",&ch);
  //
  QueryPerformanceCounter((LARGE_INTEGER*) &qu2);
  long long ti=(qu2-qu1)/fr;
  //printf("%i %i",ha,frd);
  midiOutClose(hmo);
  //
  FreeLibrary(li);
};

Charles