File I/O open()函数

2019-08-01  本文已影响0人  无无吴

Opening Files

The Open() System Call

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int open (const char *name, int flags);
int open (const char *name, int flags, mode_t mode);

Flags for open()

int testO_TRUNC()
{
    int fd = open("../FileIO/testfile.txt", O_WRONLY);
    if(fd == -1){
        perror("open");
        return -1;
    }
    close(fd);
    return 0;
}
没有O_TRUNC
int testO_TRUNC()
{
    int fd = open("../FileIO/testfile.txt", O_WRONLY | O_TRUNC);
    if(fd == -1){
        perror("open");
        return -1;
    }
    close(fd);
    return 0;
}
有O_TRUNC

很明显,带有O_TRUNC写文件时的效果就是先把文件先清空,再写入
验证如下

int testO_TRUNC()
{
    int fd = open("../FileIO/testfile.txt", O_WRONLY | O_TRUNC);
    if(fd == -1){
        perror("open");
        return -1;
    }
    char buf[5] = "aaaa";
    write(fd, buf, 5);
    close(fd);
    return 0;
}
先写一个
int testO_TRUNC()
{
    int fd = open("../FileIO/testfile.txt", O_WRONLY | O_TRUNC);
    if(fd == -1){
        perror("open");
        return -1;
    }
    char buf[5] = "bbbb";
    write(fd, buf, 5);
    close(fd);
    return 0;
}
再写一个
通过如上的实验,结论得以验证

新文件的所有者

文件所有者的uid是创建文件的进程的uid
默认行为是将文件的gid设置为创建文件的进程的gid。

新文件的权限

之前给的两个关于open函数的调用形式都是有效的。参数mode可以被忽略除非文件是被创建的,也是就说要给出O_CREAT。当你使用O_CREAT时但忘记提供mode参数的时候,那么结果是不明确的,而且非常丑陋──所以不要忘记!

int testMode()
{
    int fd = open("test1.txt", O_WRONLY | O_CREAT | O_TRUNC,
            S_IWUSR | S_IRUSR | S_IWGRP | S_IRGRP | S_IROTH);
//    int fd = open("test1.txt", O_CREAT | O_EXCL,
//                  S_IWUSR | S_IRUSR | S_IWGRP | S_IRGRP | S_IROTH);
    if(fd == -1){
        perror("testMode - open");
        return -1;
    }
    char buf[5] = "aaaa";
    write(fd, buf, 5);
    close(fd);
    return 0;
}

如果此时再用以下代码,则会发现报以下错误:

int testMode()
{
//    int fd = open("test1.txt", O_WRONLY | O_CREAT | O_TRUNC,
//            S_IWUSR | S_IRUSR | S_IWGRP | S_IRGRP | S_IROTH);
    int fd = open("test1.txt", O_CREAT | O_EXCL,
                  S_IWUSR | S_IRUSR | S_IWGRP | S_IRGRP | S_IROTH);
    if(fd == -1){
        perror("testMode - open");
        return -1;
    }
    char buf[5] = "aaaa";
    write(fd, buf, 5);
    close(fd);
    return 0;
}
创建文件但文件已存在

如果此时把文件删除,再次调用以上代码,则会发现:


试验1

也就是说明,在文件创建时没有提供写的权限,文件可以创建,但是不会被写入,并且可以看到权限的设置是按照预期的。
最后让我们先删除文件,再加入写的权限并创建文件看一下:

int testMode()
{
//    int fd = open("test1.txt", O_WRONLY | O_CREAT | O_TRUNC,
//            S_IWUSR | S_IRUSR | S_IWGRP | S_IRGRP | S_IROTH);
    int fd = open("test1.txt", O_CREAT | O_EXCL | O_WRONLY,
                  S_IWUSR | S_IRUSR | S_IWGRP | S_IRGRP | S_IROTH);
    if(fd == -1){
        perror("testMode - open");
        return -1;
    }
    char buf[5] = "aaaa";
    write(fd, buf, 5);
    close(fd);
    return 0;
}
试验2

我们发现文件按照预期权限创建,并且因为我们在创建文件时加入了写的权限,因此成功写入了想要的内容。

上一篇 下一篇

猜你喜欢

热点阅读