24. creat - 创建文件 链接到标题

函数介绍 链接到标题

creat系统调用用于创建新文件或截断已存在的文件。它是一个简化的文件创建函数,等价于open(path, O_WRONLY|O_CREAT|O_TRUNC, mode)

函数原型 链接到标题

#include <fcntl.h>
#include <sys/stat.h>
#include <unistd.h>

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

功能 链接到标题

创建新文件或清空已存在的文件,返回只写权限的文件描述符。

参数 链接到标题

  • const char *pathname: 要创建的文件路径名
  • mode_t mode: 文件权限模式(如0644)

返回值 链接到标题

  • 成功时返回文件描述符(非负整数)
  • 失败时返回-1,并设置errno

特殊限制 链接到标题

  • 文件总是以只写模式打开
  • 如果文件已存在,会被截断为0字节
  • 不支持追加模式等高级选项

相似函数 链接到标题

  • open(): 更灵活的文件打开函数
  • mkstemp(): 创建安全的临时文件

示例代码 链接到标题

#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <string.h>
#include <sys/stat.h>

int main() {
    int fd;
    
    printf("=== Creat函数示例 ===\n");
    
    // 示例1: 基本文件创建
    printf("示例1: 基本文件创建\n");
    fd = creat("test_creat.txt", 0644);
    if (fd == -1) {
        perror("创建文件失败");
    } else {
        printf("成功创建文件,fd=%d\n", fd);
        write(fd, "Hello from creat!", 17);
        close(fd);
    }
    
    // 示例2: 重复创建(会截断原文件)
    printf("示例2: 重复创建(截断原文件)\n");
    fd = creat("test_creat.txt", 0644);
    if (fd != -1) {
        printf("重新创建文件(原内容被清空)\n");
        write(fd, "New content", 11);
        close(fd);
    }
    
    // 示例3: 权限测试
    printf("示例3: 不同权限创建\n");
    int fd1 = creat("file_600.txt", 0600);  // 仅所有者读写
    int fd2 = creat("file_644.txt", 0644);  // 所有者读写,其他用户读
    int fd3 = creat("file_666.txt", 0666);  // 所有用户读写
    
    if (fd1 != -1) {
        printf("创建0600权限文件\n");
        close(fd1);
    }
    if (fd2 != -1) {
        printf("创建0644权限文件\n");
        close(fd2);
    }
    if (fd3 != -1) {
        printf("创建0666权限文件\n");
        close(fd3);
    }
    
    // 清理测试文件
    unlink("test_creat.txt");
    unlink("file_600.txt");
    unlink("file_644.txt");
    unlink("file_666.txt");
    
    return 0;
}