2014年5月22日 星期四

[C] This example show pointer how to work

[C] This example show pointer how to work



/*

 * Create a testfile.txt at the first.

 *

 * This is a example to show pointer how to work.

 *

 * 1.

 * So we allocate one block was called happy.

 * And block size is 1024.

 * We can write down like below.

 * char happy[1024] = {0};

 *

 * 2.

 * We assign one pointer was called ptr.

 * We can write down like below.

 * char *ptr = NULL;

 *

 *

 * 3. Assign block memory to pointer, then through it write function.

 * */



#include <unistd.h>

#include <fcntl.h>

#include <stdio.h>



int main()

{

    int i = 0;

    char *ptr = NULL;

    /* A nice long string */

    char happy[1024] = {0};

    printf( "Please enter a long string: " );



    /* notice stdin being passed in */

    fgets ( happy, 1024, stdin );



/* Understand what is point work

 * Point can represent a array

 * So this example is wonder example.

 * */

    ptr=happy;

    /* Create testfile.txt at the first */

    int filedesc = open("testfile.txt", O_WRONLY | O_APPEND);

    if(filedesc < 0)

        return 1;



    for (i = 0; i < 2; i++)

    {

        if(write(filedesc,ptr, sizeof(happy)) != 1024)

        {

            write(2,"There was an error writing to testfile.txt\n",43);

            return 1;

        }

    }



    return 0;

}




Related Posts:

0 意見:

張貼留言