linuxC库函数---write

1、头文件

#include<unistd.h>

2、函数原型

ssize_t write (int fd,const void * buf,size_t count);

3、返回值

如果顺利write()会返回实际写入的字节数。当有错误发生时则返回-1,错误代码存入errno中。
EINTR 此调用被信号所中断。
EAGAIN 当使用不可阻断I/O 时(O_NONBLOCK),若无数据可读取则返回此值。
EBADF 参数fd非有效的文件描述词,或该文件已关闭。

4、举例

#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>

int main(void) 
{
	printf ("write process pid: %d\n", getpid ());
 	char buf[64] = { 0 };
  	int n = 0;
  	while (1) 
  	{
    	if ((n = read (STDIN_FILENO, buf, 64)) > 0) 
		{
      		int fd = open ("data.txt", O_WRONLY|O_CREAT, 0664);
      		if (fd < 0) 
	  		{
        		perror ("open");
        		continue;
      		}   
	  	buf[n] = '\0';
      	write (fd, buf, n + 1); 
      	close (fd);
    	}   
  	}
  	return 0;
}
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>

int main (void) 
{
  	char buf[64];
  	int i;

  	printf ("read process pid: %d\n", getpid());
  	int fd = open ("data.txt", O_RDONLY);
  	if (fd < 0) 
  	{
    	perror ("open");
    	return -1;
  	}
  	int len = 0;
	int last_len = 0;
  	while (1)
	{
  		if ((len = read(fd, buf, 64)) < 0) 
  		{
    		perror ("read");
    		close (fd);
    		return -2;
  		}
  		printf ("%s", buf);
  		lseek (fd,0, SEEK_SET);
		sleep (5);
	}
	close (fd);
    return 0;
}
发布了56 篇原创文章 · 获赞 6 · 访问量 6853

猜你喜欢

转载自blog.csdn.net/qq_23929673/article/details/99536817