在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_IRUSR和S_IWUSR標志設置文件的讀取和寫入權限。這樣,只有文件的所有者(通常是創建文件的用戶)才能讀取和寫入該文件。
注意:在實際應用中,你可能需要檢查open()函數的返回值以確保文件已成功打開。此外,你還可以使用chmod()函數在程序運行時更改文件權限。