天天看点

linux系统编程–有关文件的操作(4)

文件的读取操作(以移动光标的形式进行读取)

一、了解一些操作文件的小知识

SEEK_SET(指向文件的头)

SEEK_END (指向文件的尾巴)

SEEK_CUR(指向当前光标的位置)

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

int   main()
{
         int   fd;
         char  *buf="wo hen shuai";

	     fd=open("./file1",O_RDWR);

	     if(fd==-1)
       {
          printf("open file1 failed\n");

	      fd=open("./file1",O_RDWR|O_CREAT,0600);

              if(fd>0)
	      {
	        printf("create file1  success\n");
	      }
       }

	 printf("open success:  fd=%d\n",fd);
      

	 //ssize_t write(int fd, const void *buf, size_t count);
       int n_write =write(fd,buf,strlen(buf));

        if(n_write!=-1)    
       	{
         printf("write %d btye to file\n",n_write);    
        }

//         close (fd);


  //       fd=open("./file1",O_RDWR);

  // off_t lseek(int fd, off_t offset, int whence);

	    char  *readbuf;
	 readbuf =(char*)malloc(sizeof(char)*n_write+1);
       lseek(fd,0,SEEK_SET);
/*文件写完之后,重新跳到文件的头,对文件进行读取*/

	 // ssize_t read(int fd, void *buf, size_t count);
        int  n_read=read(fd,readbuf,n_write);


	  printf("read %d,context:%s\n",n_read,readbuf);

	 close(fd);

     return 0;
}

           

运行结果和有关文件的操作(3)一致。

——@上官可编程

继续阅读