當(dāng)前位置:首頁(yè) > 嵌入式培訓(xùn) > 嵌入式學(xué)習(xí) > 講師博文 > write()函數(shù)的功能介紹及實(shí)例
功能:
向文件中寫入數(shù)據(jù)
頭文件:
#include
原型:
ssize_t write(int fd, const void *buf, size_t count);
參數(shù):
fd: 文件描述符
buf: 存放要寫入的數(shù)據(jù)的緩沖區(qū)首地址
count: 想要寫入的字節(jié)數(shù)
返回值:
>=0:成功寫入的字節(jié)數(shù),0表示什么都沒寫入
-1: 寫入失敗,并設(shè)置全局變量errno
例:
#include
#include
#include
#include
#include
#include
#include
int main(int argc, char *argv[])
{
if (argc < 2)
{
fprintf(stderr, "Usage: %s \n", argv[0]);
return -1;
}
int fd = 0;
if (0 > (fd = open(argv[1], O_WRONLY|O_CREAT|O_TRUNC, 0666)))
{
perror("open");
return -1;
}
char buf[100] = "hello world!";
int ret;
if (strlen(buf) != write(fd, buf, strlen(buf)))
{
perror("write");
return -1;
}
printf("Write file successfully!\n");
close(fd);
return 0;
}
注意:write第三個(gè)參數(shù)表示想要寫入的字節(jié)數(shù),返回值表示實(shí)際寫入的字節(jié)數(shù),-1表示出錯(cuò)。如果要查看真正寫入的字節(jié)數(shù)需要看返回值。比如套接字文件或者管道文件,有時(shí)候不能一次性把整個(gè)buf全部寫入文件,此時(shí)需要循環(huán)寫入。
例:
ssize_t mywrite(int fd, const void *buf, size_t count)
{
ssize_t size = 0;
int ret = 0;
while (size < count)
{
ret = write(fd, buf+size, count-size);
size += ret;
}
return size;
}
上述函數(shù)mywrite的功能是保證能夠成功寫入count字節(jié),mywrite的參數(shù)與write函數(shù)一樣。size表示已經(jīng)寫入的字節(jié)數(shù),當(dāng)成功寫入的字節(jié)數(shù)小于想要寫入的字節(jié)數(shù)時(shí),循環(huán)往文件中寫,從buf偏移size處開始把剩下的內(nèi)容寫入文件,直到size等于count跳出循環(huán)。
當(dāng)寫入的文件時(shí)套接字或者管道文件時(shí),有一個(gè)發(fā)送緩沖區(qū),如果緩沖區(qū)已滿,此時(shí)發(fā)送阻塞,這就是寫阻塞。如果設(shè)置為非阻塞模式O_NONBLOCK,緩沖區(qū)寫滿后,返回-1,錯(cuò)誤原因Resource temporarily unavailable。
當(dāng)寫入的文件時(shí)套接字或者管道文件時(shí), 如果讀端關(guān)閉,寫端還在向?qū)Χ藢懭霐?shù)據(jù)時(shí),此時(shí)會(huì)產(chǎn)生管道破裂信號(hào)SIGPIPE,導(dǎo)致程序終止。如果寫進(jìn)程沒有報(bào)任何錯(cuò)誤就結(jié)束,很有可能就是管道破裂造成,可以使用signal函數(shù)去捕捉該信號(hào),判斷錯(cuò)誤原因
例: signal(SIGNAL, handler);