1、write函數(shù)的詳解
ssize_t write(int fd,const void*buf,size_t count);
參數(shù)說明:
? fd:是文件描述符(write所對應(yīng)的是寫,即就是1)
? buf:通常是一個字符串,需要寫入的字符串
? count:是每次寫入的字節(jié)數(shù)
返回值:
?成功:返回寫入的字節(jié)數(shù)
?失?。悍祷?1并設(shè)置errno
? ps: 寫常規(guī)文件時,write的返回值通常等于請求寫的字節(jié)?數(shù)count, 而向終端設(shè)備或者網(wǎng)絡(luò)寫時則不一定
2、write函數(shù)使用
首先打開終端,輸入
man 2 write
?接著打開新的終端,輸入:
vi demo3.c
?輸入如下代碼:
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include<stdio.h>
#include <unistd.h>
#include<string.h>
int main()
{
int fd;
char *buf = "asdfggh";
fd = open("./file1",O_RDWR);
if(fd == -1){
printf("open file1 failed\n");
fd = open("./file1",O_RDWR|O_CREAT,0600);
if(fd>0){
printf("create file1 success\n");
}
}
printf("open susceess : fd = %d\n",fd);
write(fd,buf,strlen(buf));
close(fd);
return 0;
}
保存退出,接著輸入如下:
vi demo3.c
./a.out
vi file1
?文章來源:http://www.zghlxwxcb.cn/news/detail-679383.html
?文章來源地址http://www.zghlxwxcb.cn/news/detail-679383.html
到了這里,關(guān)于ubuntu學(xué)習(xí)(四)----文件寫入操作編程的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!