write()与 read() 函数用法(C语言)
write()函数:将数据写入已经打开的文件内。
头文件:#include <unistd.h>
函数原型:ssize write(int fd,const void * buf,size_t count);
fd: 文件描述符。
buf: 定义的缓冲区,是一个指针,指向一段内存。
count: 写入文件的字节数。
返回值:成功返回写入文件的字节数,失败返回-1。
read()函数: 读取指定文件中的文件内容。
头文件:#include <unistd.h>
函数原型: ssize read(int fd, void *buf, size_t count);
fd: 文件描述符,读到文件末尾返回0。
buf: 是接收数据的缓冲区。
count: 读取字节数的大小,不能超过buf的大小。
返回值:成功返回实际读取的字节数,失败返回-1。
注意:在写完文件以后读取文件之前,要先关闭文件再重新打开文件,否则会出现错误。
因为写完文件以后文件流指针会指向文件末尾,这时再读取文件就会失败,使用上面的方法就避免了这种情况哦。
示例代码如下:
#include<stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include<string.h>
int main(int argc, char const *argv[])
{
int fd;
int ret;
char buf[32] = "hello world!";
char buf2[32] = {0};
fd = open("t.txt",O_RDWR|O_APPEND|O_CREAT,0666);
if(fd < 0)
{
printf("open file errn");
return 0;
}
printf("open successn");
ret = write(fd,buf,strlen(buf));
if(ret < 0)
{
perror("write:");
goto END;
}
printf("write count= %dn",ret);
close(fd);
fd = open("t.txt",O_RDWR|O_APPEND|O_CREAT,0666);
ret = read(fd,buf2,32);
if(ret < 0)
{
perror("read:");
goto END;
}
printf("read bif2= %sn",buf2);
END:
close(fd);
return 0;
}