User Tools

Site Tools


cs_lang:c

This is an old revision of the document!


Learning C

Simple examples

Hello World

/* Hello World program */
 
#include<stdio.h>
 
main()
{
    printf("Hello World");
 
 
}

Compile and run the program:

$ gcc -Wall hello.c -o hello.out
hello.c:6: warning: return type defaults to ‘int’
hello.c: In function ‘main’:
hello.c:10: warning: control reaches end of non-void function
 
$ ./hello.out 
Hello World

Increment a number

#include "stdio.h"
 
char  line[100];
int   value;
 
int main()
{
    printf("Enter a value:");
    fgets(line, sizeof(line), stdin);
    sscanf(line, "%d", &value);
 
    printf("Inc: %d\n", value + 1);
    return value+1;
}
$ gcc -Wall test1.c 
cedric@debian:~$ ./a.out 
Enter a value:41
Inc: 42

Equivalent in python

>>> def inc():
...     value = raw_input("Enter a value:")
...     print "Inc:", int(value)+1
... 
>>> inc()
Enter a value:41
Inc: 42

Read a file

#include <stdio.h>   /* required for file operations */
 
FILE *fr;            /* declare the file pointer */
 
main()
 
{
   char line[1024];
 
   fr = fopen ("./file.txt", "rt");  /* open the file for reading */
   /* "rt" means open the file for reading text */
 
   while(fgets(line, 1024, fr) != NULL)
   {
         printf ("%s\n", line);
   }
   fclose(fr);  /* close the file prior to exiting the routine */
}

Equivalent in python

for line in open("./file.txt", "r"):
    print line
cs_lang/c.1310464401.txt.gz · Last modified: 2011/07/12 11:53 by cedric