MST
星途 面试题库

面试题:C语言Linux文件写入系统调用中的错误处理

在Linux环境下用C语言进行文件写入系统调用时,可能会遇到多种错误情况,如文件不存在、权限不足等。请详细阐述如何在代码中有效地检测和处理这些常见错误,并举例说明。
12.4万 热度难度
编程语言C

知识考点

AI 面试

面试题答案

一键面试

1. 检测和处理文件不存在错误

在使用 open 系统调用打开文件以便写入时,如果文件不存在,并且没有使用 O_CREAT 标志,open 会返回 -1 并设置 errnoENOENT

#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>

int main() {
    int fd = open("nonexistent_file.txt", O_WRONLY);
    if (fd == -1) {
        if (errno == ENOENT) {
            printf("文件不存在,可考虑使用O_CREAT标志创建文件\n");
        } else {
            perror("open error");
        }
        return 1;
    }
    close(fd);
    return 0;
}

2. 检测和处理权限不足错误

当用户没有足够的权限打开或写入文件时,open 也会返回 -1,并设置 errnoEACCES

#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>

int main() {
    int fd = open("/root/somefile.txt", O_WRONLY);
    if (fd == -1) {
        if (errno == EACCES) {
            printf("权限不足,检查文件权限或使用合适的用户运行\n");
        } else {
            perror("open error");
        }
        return 1;
    }
    close(fd);
    return 0;
}

3. 检测和处理写入错误

在使用 write 系统调用写入文件时,可能会遇到错误,比如磁盘空间不足等。write 会返回 -1 并设置相应的 errno

#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>

int main() {
    int fd = open("test.txt", O_WRONLY | O_CREAT, 0644);
    if (fd == -1) {
        perror("open error");
        return 1;
    }
    const char *msg = "Hello, world!";
    ssize_t bytes_written = write(fd, msg, strlen(msg));
    if (bytes_written == -1) {
        perror("write error");
        close(fd);
        return 1;
    }
    close(fd);
    return 0;
}

在上述代码中,通过检查系统调用的返回值,并结合 errno 判断具体的错误类型,从而有效地处理在文件写入过程中可能遇到的常见错误。