write:
#include <unistd.h>
ssize_t write(int fd, const void *buf, size_t count);
fd:要寫入的文件的描述符。
buf:要寫入的數據所存放的緩衝區。
count:要寫入的字節數,並不是緩衝區的大小
返回值:若成功返回已寫的字節數,出錯則返回-1並設置變量errno的值。
int main3()
{
int fd = open("b.c",O_WRONLY | O_CREAT,0777);
if(fd == -1)
{
perror("open ");
return -1;
}
char buf[SIZE] = {0};//設置一個緩衝區
while(1)
{
fgets(buf,SIZE,stdin);
if(strncmp ("end",buf,3) == 0)//輸入end時退出循環
break;
//返回值
ssize_t ret = write (fd,buf,strlen(buf));
if(ret == -1)
{
perror("write ");
}
printf("要寫的字節數:%d, 實際寫的字節數:%d\n",SIZE,ret);
}
close(fd);
return 0;
}
/*
close()系統調用關閉一個打開的文件。
#include <unistd.h>
int close(int fd);
Returns 0 on success, or –1 on error
各參數及返回值的含義如下:
fd:要關閉的文件的描述符。
返回值:若成功返回0,出錯則返回-1。
*/
/*
lseek:
#include <sys/types.h>
#include <unistd.h>
off_t lseek(int fildes, off_t offset, int whence);
返回值:成功返回文件偏移量,失敗返回-1
參數whence必需是以下三個常量之一:
SEEK_SET:將文件偏移量設置在距文件開始處offset個字節。
SEEK_CUR:將文件偏移量設置在其當前值加offset,offset可正可負。
SEEK_END:將文件偏移量設置爲文件長度加offset,offset可正可負。
*/
int main()
{ //打開要讀的文件
int fd = open("b.c",O_WRONLY | O_CREAT,0777);
if(fd == -1)
{
perror("open ");
return -1;
}
lseek (fd,10,SEEK_CUR);//設置偏移指針
char *buf = "hello";
write (fd,buf,strlen(buf));
close(fd);
return 0;
}
文件操作的系統調用之write ,close, lseek
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.