c語(yǔ)言write函數(shù)如何使用

小億
143
2023-12-12 01:43:40

在C語(yǔ)言中,可以使用write函數(shù)來(lái)將數(shù)據(jù)寫(xiě)入文件或套接字。

函數(shù)原型如下:

ssize_t write(int fd, const void *buf, size_t count);

參數(shù)說(shuō)明:

  • fd:文件描述符或套接字,表示要寫(xiě)入的目標(biāo)文件或套接字。
  • buf:要寫(xiě)入的數(shù)據(jù)的緩沖區(qū)指針。
  • count:要寫(xiě)入的數(shù)據(jù)的字節(jié)數(shù)。

返回值:

  • 成功時(shí),返回實(shí)際寫(xiě)入的字節(jié)數(shù)。
  • 失敗時(shí),返回-1,并設(shè)置errno。

下面是一個(gè)簡(jiǎn)單的例子,展示了如何使用write函數(shù)將字符串寫(xiě)入文件:

#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>

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

在上面的例子中,我們首先使用open函數(shù)打開(kāi)一個(gè)名為output.txt的文件,如果打開(kāi)失敗則會(huì)返回-1,并通過(guò)perror函數(shù)打印錯(cuò)誤信息。然后使用write函數(shù)將字符串str寫(xiě)入文件中,并檢查返回值。最后使用close函數(shù)關(guān)閉文件。

需要注意的是,write函數(shù)是一個(gè)阻塞函數(shù),如果寫(xiě)入的數(shù)據(jù)量過(guò)大,可能會(huì)導(dǎo)致程序阻塞??梢允褂脀rite函數(shù)的返回值來(lái)判斷實(shí)際寫(xiě)入的字節(jié)數(shù),從而進(jìn)行錯(cuò)誤處理。

0