1、要用到unistd.h頭文件。
2、 Write函數
用法:
write函數所在的頭文件為 <unistd.h>
write有兩種用法。壹種是:
ssize_twrite(int handle, void *buf, int nbyte);
handle 是文件描述符;
buf是指定的緩沖區,即指針,指向壹段內存單元;
nbyte是要寫入文件指定的字節數;返回值:寫入文檔的字節數(成功);-1(出錯)
write函數把buf中nbyte寫入文件描述符handle所指的文檔,成功時返回寫的字節數,錯誤時返回-1.
另壹種是:write(const char* str,int n)
str是字符指針或字符數組,用來存放壹個字符串。n是int型數,它用來表示輸出顯示字符串中字符的個數。
write("string",strlen("string");表示輸出字符串常量
3、程序示例:
#include?<stdio.h>#include?<stdlib.h>
#include?<fcntl.h>
#include?<sys\stat.h>
#include?<io.h>
#include?<string.h>
int?main(void)
{
int?*handle;?char?string[40];
int?length,?res;/*?Create?a?file?named?"TEST.$$$"?in?the?current?directory?and?write?a?string?to?it.?If?"TEST.$$$"?already?exists,?it?will?be?overwritten.?*/
if?((handle?=?open("TEST.$$$",?O_WRONLY?|?O_CREAT?|?O_TRUNC,?S_IREAD?|?S_IWRITE))?==?-1)
{
printf("Error?opening?file.\n");
exit(1);
}
strcpy(string,?"Hello,?world!\n");
length?=?strlen(string);
if?((res?=?write(handle,?string,?length))?!=?length)
{
printf("Error?writing?to?the?file.\n");
exit(1);
}
printf("Wrote?%d?bytes?to?the?file.\n",?res);
close(handle);?return?0;?}