【Linux】深入理解系统文件操作(1w字超详解)
    		       		warning:
    		            这篇文章距离上次修改已过442天,其中的内容可能已经有所变动。
    		        
        		                
                由于篇幅过长,这里只能提供一个关键函数的示例代码。
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
 
int main() {
    // 打开文件
    int fd = open("/path/to/file", O_RDWR | O_CREAT, S_IRUSR | S_IWUSR);
    if (fd == -1) {
        perror("open");
        exit(EXIT_FAILURE);
    }
 
    // 写入数据
    const char *buf = "Hello, World!";
    ssize_t bytes_written = write(fd, buf, sizeof(buf));
    if (bytes_written == -1) {
        perror("write");
        close(fd); // 写入失败,关闭文件
        exit(EXIT_FAILURE);
    }
 
    // 移动文件指针
    int seek_result = lseek(fd, 0, SEEK_SET);
    if (seek_result == -1) {
        perror("lseek");
        close(fd); // 移动文件指针失败,关闭文件
        exit(EXIT_FAILURE);
    }
 
    // 读取数据
    char read_buf[100];
    ssize_t bytes_read = read(fd, read_buf, sizeof(read_buf) - 1);
    if (bytes_read == -1) {
        perror("read");
        close(fd); // 读取失败,关闭文件
        exit(EXIT_FAILURE);
    }
    read_buf[bytes_read] = '\0'; // 确保字符串以 null 结尾
 
    printf("Read: %s\n", read_buf);
 
    // 关闭文件
    if (close(fd) == -1) {
        perror("close");
        exit(EXIT_FAILURE);
    }
 
    return 0;
}这段代码展示了如何在Linux下使用标准库函数对文件进行基本操作,包括创建、写入、读取和关闭文件。同时,代码中包含了错误处理,以确保在出现问题时程序能够给出有用的反馈信息。
评论已关闭