溫馨提示×

linux cwrite如何設置寫入權限

小樊
101
2024-12-29 08:43:19
欄目: 智能運維

在Linux系統中,cwrite()函數用于向文件描述符寫入數據

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

int main() {
    int fd;
    const char *file_path = "/tmp/testfile.txt";
    const char *data = "Hello, World!";
    size_t data_size = strlen(data);

    // 打開文件,如果文件不存在則創建,并設置相應的權限
    fd = open(file_path, O_CREAT | O_WRONLY, S_IRUSR | S_IWUSR);
    if (fd == -1) {
        perror("open");
        exit(EXIT_FAILURE);
    }

    // 將數據寫入文件
    ssize_t bytes_written = write(fd, data, data_size);
    if (bytes_written != data_size) {
        perror("write");
        close(fd);
        exit(EXIT_FAILURE);
    }

    // 關閉文件描述符
    close(fd);

    printf("Data written to file: %s\n", file_path);
    return 0;
}

在這個示例中,我們使用open()函數打開或創建一個名為testfile.txt的文件,并使用S_IRUSRS_IWUSR標志設置文件的讀取和寫入權限。這樣,只有文件的所有者(通常是創建文件的用戶)才能讀取和寫入該文件。

注意:在實際應用中,你可能需要檢查open()函數的返回值以確保文件已成功打開。此外,你還可以使用chmod()函數在程序運行時更改文件權限。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女