c - "creat"Unix系统调用

标签 c linux unix system-calls

我正在使用 creat 系统调用来创建文件。下面是创建文件的程序

#include<stdio.h>
#include<fcntl.h>
void main()
{
    int fd=creat("a.txt",S_IRWXU|S_IWUSR|S_IRGRP|S_IROTH);
    printf("fd  = %d\n",fd);
}

因此,首先,程序会创建一个名为 a.txt 的文件,并具有适当的权限。如果我再执行一次 a.out,就会创建新的 a.txt。但是,文件的 inode 保持不变。怎么样,会怎样。

$ ./a.out
fd  = 3
$ ls -li a.txt
2444 -rw-r--r-- 1 mohanraj mohanraj 0 Aug 27 15:02 a.txt
$ cat>a.txt
this is file a.txt
$ ./a.out
fd  = 3
$ cat a.txt
$ls -li a.txt
2444 -rw-r--r-- 1 mohanraj mohanraj 0 Aug 27 15:02 a.txt
$

在上面的输出中,a.txt 的内容为“This is file a.txt”。一旦我执行 a.out,就会创建新的 a.txt。但是, inode 2444 保持不变。那么,creat 系统调用是如何工作的呢?

提前致谢。

最佳答案

creat 只创建一个不存在的文件。如果它已经存在,它就会被截断。

creat(filename, mode);

相当于

open(filename, O_WRONLY|O_CREAT|O_TRUNC, mode);

并且在open(2)中指定文档:

O_CREAT
If the file does not exist it will be created.

关于c - "creat"Unix系统调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32246011/

相关文章:

c - Linux、时区和夏令时

C 当前时间

linux - 参数数量要求输入验证

c - Linux 执行程序; ls 无法访问 |,没有那个文件或目录

c - 如何在 C 中调试不干净的套接字关闭?

c - 当 SIGINT 信号被忽略时打印字符串

shell - rm -rf/base-dir-path/*/work 与/base-dir-path/*/*/work 不同

c - 如何在 dbx 中打印长字符串的完整值?

c - ASturct arr[] 和 ASturct * arr[] 之间的区别

从Windows cmd提示符远程访问MySQL