GNU/Linux编程指南学习笔记之七:系统编程----I/O Routines (续)

来源:互联网 发布:曲婉婷母亲 知乎 编辑:程序博客网 时间:2024/05/16 15:01

Types of Files

  1. Regular File

下面的示例程序中用到了大多数上面讲到的系统调用

***************************************************************

/*filedes_io.c*/

#include <sys/types.h>

#include <sys/stat.h>

#include <sys/file.h>

#include <fcntl.h>

#include <unistd.h>

#include <assert.h>

#include <errno.h>

#include <string.h>

#include <stdio.h>

 

char sample1[] = "This is sample data 1/n";

char sample2[] = "This is sample data 2/n";

char data[16]; 

 

main()

{

    int fd;

    int rc;

    struct stat statbuf;

 

    /*Create the file*/

    printf("Creating file/n");

    fd = open("junk.out", O_WRONLY|O_CREAT|O_TRUNC, 0666);

    assert(fd>=0);

 

    rc = write(fd, sample1, strlen(sample1));

    assert(rc == strlen(sample1));

 

    close(fd);

 

    /*Append to the file*/

    printf("Appending to file/n");

    fd = open("junk.out", O_WRONLY|O_APPEND);

    assert(fd>=0);

 

    printf("locking file/n");

    rc = flock(fd, LOCK_EX);

    assert(rc == 0);

 

    /*sleep so you can try running two copies at one time*/

    printf("sleeping for 10 senconds/n");

    sleep(10);

 

    printf("writting data/n");

    rc = write(fd, sample2, strlen(sample2));

    assert(rc == strlen(sample2));

 

    printf(unlocking file/n);

    rc = flock(fd, LOCK_UN);

    assert(rc == 0);

 

    close(fd);

 

    /*Read the file*/

    printf("Reading file/n");

    fd = open("junk.out", O_RDONLY);

    assert(fd>=0);

 

    while(1){

        rc = read(fd, data, sizeof(data));

        if(rc>0){

            data[rc] = 0;  /*terminate string*/

            printf("Data read (rc=%d):<%s>/n", rc, data);

        }else if(rc == 0){

            printf("End of file read/n");

            break;

        }else{

            perror("read error");

            break;

        }

    }

    close(fd);

 

    /*Fiddle with inode*/

    printf("Fiddling with inode/n");

    fd = open("junk.out", O_RDONLY);

    assert(fd>=0);

 

    printf("changing file mode");

    rc = fchmod(fd, 0600);

    assert(rc == 0);

    if(getuid() == 0){

        printf("changing file owner/n");

        /*If we are root, change file to owner nobody,*/

        /*group nobody(assuming nobody == 99)*/

        rc = fchmod(fd, 99, 99);

        assert(rc == 0);

    }else{

        printf("not changing file owner/n");

    }

 

    fstat(fd, &statbuf);

    printf("file mode = %o (octal)/n", statbuf.st_mode);

    printf("Owner uid = %d/n", statbuf.st_uid);

    printf("Owner gid = %d/n", statbuf.st_gid);

 

    close(fd);

}

 

  1. Tape I/O

 

  1. Serial port I/O
  2. Printer Port
  3. Sound Card
原创粉丝点击