文件操作:open write read lseek

#include <sys/types.h>

#include <sys/stat.h>

#include <fcntl.h>

#include <stdio.h>

#include <unistd.h>



int main(void)

{

char buf[100] = {0};

int fd, size, pur;



if ((fd = open("hello", O_CREAT | O_TRUNC | O_RDWR, 0666)) < 0) {

   /*O_RDONLY, O_WRONLY, O_RDWR, O_APPEND, model is w r x*/
   /*O_APPEND is move to the end before every write*/
   /*guaranteed atomic operate each write*/

   perror("open fail");

} else {

   printf("open and create file:hello with fd :%d\n",fd);

}



/* SEEK_SET SEEK_CUR SEEK_END return current vfo point */

pur = lseek(fd, 5, SEEK_SET);

printf("pur :%d\n", pur);

/* auto fill 0 when len > real string */

if ((size = write( fd, "Hello! World!", 17)) < 0){

   perror("write:");

} else {

   printf("Write:%s \n","Hello! World!");

}



pur = lseek(fd, 0, SEEK_CUR);

printf("pur :%d\n", pur);



/* read should from start, if start with hole ,return buf null */

/*we put 5 hole , start 4 offset, will see result buf is null ,start 5 will get right result*/

pur = lseek(fd, 4, SEEK_SET);

printf("pur :%d\n", pur);



if ((size = read(fd, buf, 100))<=0) {

   perror("read fail");

} else {

   printf("read form file:%s \n",buf);

}



pur = lseek(fd, 0, SEEK_CUR);

printf("pur :%d\n", pur);



if (close(fd) < 0 )    {

   perror("close fail");

} else

   printf("Close hello\n");

return 0;

}

result:

open and create file:hello with fd :3

pur :5

Write:Hello! World! 

pur :22

pur :4

read form file: 

pur :22

Close hello

 

start 5 hole, pur = lseek(fd, 5, SEEK_SET) :

 

open and create file:hello with fd :3

pur :5

Write:Hello! World! 

pur :22

pur :5

read form file:Hello! World! 

pur :22

Close hello

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章