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

Read a file

#include <iostream.h>
#include <fstream.h>
 
int main ()
{
        //  Open the file
        ofstream inputFile ("./file.txt", ios::in);
        // Test
        if (!inputFile)
        {
                cerr << "Error" << endl;
                exit (1);
        }
        char buf [1024];
        //  Until there are no more lines in the file,
        //  read and display it.
        while (!inputFile.eof())
        {
                inputFile.getline (buf,1024);;
                cout << buf << endl;;
        }
        // Close the file
        inputFile.close ();;
}

Equivalent in python

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