C 程式設計/POSIX 參考/unistd.h/write
外觀
write 系統呼叫將資料(以呼叫者指定的位元組為單位)從程式中使用者宣告的緩衝區寫入呼叫程序提供的檔案。在大多數現代作業系統中,需要將資料寫入檔案系統中儲存的檔案的程式使用 Write 系統呼叫。檔案由從先前呼叫 open 獲取的檔案描述符標識。
因此,Write 接受三個引數
- 檔案的 檔案描述符(fd)。
- 將資料寫入檔案的緩衝區(buf)。
- 要從緩衝區讀取的位元組數(nbytes)。
write 系統呼叫介面[1][2][3] 由 POSIX 規範標準化。透過呼叫 write 函式將資料寫入檔案。函式原型為
ssize_t write(int fd, const void *buf, size_t nbytes);
| 引數 | 描述 |
|---|---|
fd |
這是從對 open 的呼叫中獲得的檔案描述符。它是一個整數值。值 0、1、2 分別可以用於標準輸入、標準輸出和標準錯誤。 |
buf |
它指向一個字元陣列,該陣列可用於儲存從 fd 指向的檔案中獲取的內容。 |
nbytes |
它指定要從檔案寫入字元陣列的位元組數。 |
在上面的語法中,ssize_t 是一個 typedef。它是在 sys/types.h 中定義的帶符號資料型別。sizeof 運算子生成一個型別為 size_t 的整數值。[4]
write 函式返回成功寫入陣列的位元組數,該位元組數有時可能小於指定的 nbytes。如果遇到錯誤,它將返回 -1。
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
int main (int argc, char *argv[])
{
int fd1;
char buf[128];
fd1 = open(argv[1], O_WRONLY | O_CREAT);
if (fd1 == -1) {
perror("File cannot be opened");
return EXIT_FAILURE;
}
/* Enter the data to be written into the file */
scanf("%127s", buf);
write(fd1, buf, strlen(buf)); /* fd1 is the file descriptor, buf is the character array used to
hold the data, strlen(buf) informs the function that the number of bytes equal to the length of the
string in the buffer need to be copied */
close(fd1);
return 0;
}
以下列出了一些[5][6] 在寫入檔案時可能遇到的錯誤。這些錯誤是在 errno.h 中列出的宏。
| 錯誤編號 | 錯誤 | 含義 |
|---|---|---|
5 |
EIO |
低階錯誤,通常與硬體讀/寫操作有關。 |
9 |
EBADF |
檔案描述符 fd 無效,或正在嘗試寫入以“只讀”模式開啟的檔案。 |
14 |
EFAULT |
函式中指定的地址是無效地址。 |
22 |
EINVAL |
與函式一起傳遞的引數無效。 |
28 |
ENOSPC |
磁碟上沒有可用空間進行寫入。 |
- ↑ http://www.unix.com/man-page/FreeBSD/2/write/ Write 手冊頁
- ↑ http://www.gnu.org/s/hello/manual/libc/I_002fO-Primitives.html#I_002fO-Primitives I/O 原語
- ↑ http://pubs.opengroup.org/onlinepubs/007904875/functions/write.html
- ↑ C 程式語言。Brian Kernighan & Dennis Ritchie. 印度:PHI Learning Private Limited. ISBN 978-81-203-0596-0.
- ↑ http://www.gnu.org/s/hello/manual/libc/Error-Codes.html GNU C 庫手冊
- ↑ http://www.ibm.com/developerworks/aix/library/au-errnovariable/ IBM 列出錯誤的頁面