A. 在C語言中要用到write和read函數要用到什麼頭文件
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<sysstat.h>
#include<io.h>
#include<string.h>
intmain(void)
{
int*handle;charstring[40];
intlength,res;/*Createafilenamed"TEST.$$$".If"TEST.$$$"alreadyexists,itwillbeoverwritten.*/
if((handle=open("TEST.$$$",O_WRONLY|O_CREAT|O_TRUNC,S_IREAD|S_IWRITE))==-1)
{
printf("Erroropeningfile. ");
exit(1);
}
strcpy(string,"Hello,world! ");
length=strlen(string);
if((res=write(handle,string,length))!=length)
{
printf("Errorwritingtothefile. ");
exit(1);
}
printf("Wrote%dbytestothefile. ",res);
close(handle);return0;}
B. C語言中的Write函數
write()寫文件函數
原形:int write(int handle,char *buf,unsigned len)
功能:將緩沖區的數據寫入與handle相聯的文件或設備中,handle是從creat、open、p或p2調用中得到的文件句柄。
對於磁碟或磁碟文件,寫操作從當前文件指針處開始,對於用O_APPEND選項打開的文件,寫數據之前,文件指針指向EOF;對於設備,位元組被直接傳送到設備中。
(2)write頭文件擴展閱讀:
用法
頭文件:<unistd.h>
write有兩種用法。一種是:ssize_t write(int fd, const void *buf, size_t nbyte);
fd:文件描述符;
buf:指定的緩沖區,即指針,指向一段內存單元;
nbyte:要寫入文件指定的位元組數;
返回值:寫入文檔的位元組數(成功);-1(出錯)
write函數把buf中nbyte寫入文件描述符handle所指的文檔,成功時返回寫的位元組數,錯誤時返回-1.
另一種是: write(const char* str,int n)
str是字元指針或字元數組,用來存放一個字元串。n是int型數,它用來表示輸出顯示字元串中字元的個數。
write("string",strlen("string");表示輸出字元串常量