函数原型>
int creat(const char *__file, mode_t __mode);
返回值>
creat( ) 会返回新的文件描述词,若有错误发生则会返回-1,并把错误代码设给errno。
1、EEXIST 参数pathname所指的文件已存在。
2、EACCESS 参数pathname所指定文件不符合所要求测试的权限。
3、EROFS 欲打开写入权限的文件存在于只读文件系统内。
4、EFAULT 参数pathname指针超出可存取的内存空间。
5、EINVAL 参数mode不正确。
6、ENAMETOOLONG 参数pathname太长。
7、ENOTDIR 参数pathname为一目录。
8、ENOMEM 核心内存不足。
9、ELOOP 参数pathname有过多符号连接问题。
10、EMFILE 已达到进程可同时打开的文件数上限。
11、ENFILE 已达到系统可同时打开的文件数上限
creat( )无法建立特别的装置文件,如果需要请使用mknod( )
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int main(int argc, char const *argv[])
{
if (argc != 2)
{
printf("请输入文件名!\n");
exit(1);
}
int fd = creat(argv[1], S_IRWXU | S_IRWXG | S_IRWXO);
// errno: 系统的全局变量(所有应用程序都可以访问的),保存错误编号
if (fd == -1)
{
printf("创建文件失败!\n");
exit(1);
}
int fd1 = creat("world.txt", 0655);
if (fd1 == -1)
{
printf("创建文件world.txt失败!\n");
exit(1);
}
return 0;
}
运行结果:
superlan@GodFather:~/C_Language/file_io$ ./a.out hello.txt
superlan@GodFather:~/C_Language/file_io$ ls
a.out file_demo.c hello.txt lseek_return.c read_line_by_line.c read_line.c three_hello.c world.txt
superlan@GodFather:~/C_Language/file_io$ ls -l
总计 36
-rwxrwxr-x 1 superlan superlan 16048 7月 30 14:44 a.out
-rw-rw-r-- 1 superlan superlan 658 7月 30 14:47 file_demo.c
-rwxrwxr-x 1 superlan superlan 0 7月 30 14:44 hello.txt
-rwxrwxrwx 1 superlan superlan 442 4月 5 20:56 lseek_return.c
-rwxrwxrwx 1 superlan superlan 2070 5月 26 17:17 read_line_by_line.c
-rwxrwxrwx 1 superlan superlan 884 4月 6 19:25 read_line.c
-rwxrwxrwx 1 superlan superlan 1317 4月 6 16:12 three_hello.c
-rw-r-xr-x 1 superlan superlan 0 7月 30 14:44 world.txt