MST

星途 面试题库

面试题:C语言中Linux文件写入系统调用的基本流程

请简述在Linux环境下,使用C语言进行文件写入系统调用的基本步骤,并给出一个简单示例代码,说明如何打开一个文件、写入数据以及关闭文件。
44.9万 热度难度
编程语言C

知识考点

AI 面试

面试题答案

一键面试
  1. 基本步骤
    • 打开文件:使用open系统调用,指定文件名、打开模式(如O_WRONLY只写、O_CREAT若文件不存在则创建等)和文件权限(如0666表示所有者、组和其他用户都有读写权限)。
    • 写入数据:使用write系统调用,指定文件描述符(由open返回)、要写入的数据缓冲区指针以及要写入的数据长度。
    • 关闭文件:使用close系统调用,指定文件描述符,释放文件资源。
  2. 示例代码
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>

int main() {
    const char *filename = "test.txt";
    const char *data = "Hello, this is some data to write.\n";
    int fd;
    ssize_t bytes_written;

    // 打开文件
    fd = open(filename, O_WRONLY | O_CREAT, 0666);
    if (fd == -1) {
        perror("open");
        return 1;
    }

    // 写入数据
    bytes_written = write(fd, data, strlen(data));
    if (bytes_written == -1) {
        perror("write");
        close(fd);
        return 1;
    }

    // 关闭文件
    if (close(fd) == -1) {
        perror("close");
        return 1;
    }

    printf("Data written successfully.\n");
    return 0;
}