歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux基礎 >> Linux技術 >> Linux系統編程學習筆記

Linux系統編程學習筆記

日期:2017/3/3 12:43:15   编辑:Linux技術

一、
open()
函數的原型

man 2 open
可以得到
open()
函數的原型的包含頭文件如下所示:
[code]#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

int open(const char *pathname, int flags);//文件已存在
int open(const char *pathname, int flags, mode_t mode);//文件不存在

二、實例

下面是一個簡單的
open()
函數的使用,對於參數flags比較常使用的有O_RDONLY、O_WRONLY、O_CREAT、O_APPEND:
[code]#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>

int main(int argc, char * argv[])
{
    int fd;
    char  buf[1024] = "deng";
    if(argc < 2)
    {
        printf("./app filename\n");
        exit(1);
    }
    umask(0);
    fd = open(argv[1], O_CREAT | O_RDWR, 0644);
    if(fd < 0)
    {
        perror("open");
        exit(1);
    }
//  fd = open(argv[1],  O_RDWR | O_APPEND);
    if(write(fd, buf, strlen(buf)) < 0)
    {
        perror("write");
        exit(1);
    }
    printf("fd = %d\n", fd);
    close(fd);  

    return 0;
}

Copyright © Linux教程網 All Rights Reserved