zoukankan      html  css  js  c++  java
  • Unix系统编程(四)creat系统调用

    我好疑惑啊,creat系统调用为啥没有以e结尾呢?搞得我每次都怀疑我敲错了。

    在早期的UNIX实现中,open只有两个参数,无法创建新文件,而是使用creat系统调用创建并打开一个新文件。

    int creat(const char *pathname, mode_t mode);

    creat系统调用根据pathname参数创建并打开一个文件,如果文件已经存在,则打开文件,并清空文件内容,将其长度清0。

    creat返回一个文件描述符,供后续系统调用使用。

    creat系统调用等价于:

    fd = open(pathname, O_WRONLY | O_CREAT | O_TRUNC, mode)

    要注意下使用creat的后果啊,文件内容会被清空掉,文件长度为0哦。

    由于open的flags参数可以对文件打开提供更多的控制,所以现在对creat的使用已经不多见了。

    这里还是把open的例子拿过来用一下吧。

    用creat打开一个文件,并向其中写入几句话。

    #include <sys/types.h>
    #include <sys/stat.h>
    #include <fcntl.h>
    #include <stdlib.h>
    #include <stdio.h>
    #include <unistd.h>
    #include <string.h>
    
    int main(int argc, char *argv[]) {
    
            int fd;
            char buf[1024] = "I love Beijing TianAnmen
    ";
    
            /* argc */
            if(argc < 2) {
                    printf("Usage: ./creat filename
    ");
                    exit(1);
            }
    
            /* if creat file correctly */
            if((fd = creat(argv[1], 0644)) == -1) {
                    printf("creat file error
    ");
                    exit(1);
            }
    
            /* write something */
            write(fd, buf, strlen(buf));
            printf("fd = %d
    ", fd);
            /* close fd */
            close(fd);
            return 0;
    }

     说实话,这个代码着色真是一言难尽。

  • 相关阅读:
    TSQL Beginners Challenge 1
    SQL拾遗
    简易实体生成方式
    CTE-递归[2]
    编号处理
    行列转换/横转竖
    OUTPUT、Merge语句的使用
    关于SQL IO的一些资料
    对左值(lvalue)和右值(rvalue)的两种理解方式
    跨平台判断64位和32位开发的一些宏定义
  • 原文地址:https://www.cnblogs.com/tuhooo/p/8639143.html
Copyright © 2011-2022 走看看