文件操作:open write read lseek

本文深入探讨了使用C语言进行文件操作的方法,包括文件的创建、读写及定位等关键过程。通过示例代码,展示了如何利用sys/types.h、sys/stat.h、fcntl.h、stdio.h和unistd.h等头文件中的函数实现对文件的精确控制。文章还解析了O_CREAT、O_TRUNC、O_RDWR等文件打开模式的作用,以及lseek和write函数在文件读写中的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值