linuxC library functions --- lseek

1, header files

#include <sys/types.h>
#include <unistd.h>

2, the function prototype

off_t lseek(int filde,off_t offset ,int whence);

3, the return value

当调用成功时则返回目前的读写位置,也就是距离文件开头多少个字节。若有错误则返回-1,errno 会存放错误代码。
可能设置erron的错误代码:
EBADF: fildes不是一个打开的文件描述符。
ESPIPE:文件描述符被分配到一个管道、套接字或FIFO。
EINVAL:whence取值不当

4, Parameter Meaning

whence为下列其中一种:(SEEK_SET,SEEK_CUR和SEEK_END和依次为0,1和2).
SEEK_SET 将读写位置指向文件头后再增加offset个位移量。
SEEK_CUR 以目前的读写位置往后增加offset个位移量。
SEEK_END 将读写位置指向文件尾后再增加offset个位移量。
当whence 值为SEEK_CUR 或SEEK_END时,参数offet允许负值的出现。
下列是较特别的使用方式:
1) 欲将读写位置移到文件开头时:
lseek(int fildes,0,SEEK_SET);
2) 欲将读写位置移到文件尾时:
lseek(int fildes,0,SEEK_END);
3) 想要取得目前文件位置时:
lseek(int fildes,0,SEEK_CUR);

5, for example

#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;
}
#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;
}

Published 56 original articles · won praise 6 · views 6847

Guess you like

Origin blog.csdn.net/qq_23929673/article/details/99537496