linux读文件代码,linux c 文件 read(读) 和 write (写) 代码分析

read code:

[[email protected] 03]# cat ex03-read-01.c

/*文件ex03-open-03.c,

O_CREAT和O_EXCL的使用*/

#include

#include

#include

#include

int main(void)

{

int fd = -1,i;

ssize_t size = -1;

/*存放数据的缓冲区*/

char buf[10];

char filename[] = "test.txt";

/*打开文件,如果文件不存在,则报错*/

fd = open(filename,O_RDONLY);

if(-1 == fd){

/*文件已经存在*/

printf("Open file %s failure,fd:%d\n",filename,fd);

}       else    {

/*文件不存在,创建并打开*/

printf("Open file %s success,fd:%d\n",filename,fd);

}

/*循环读取数据,直到文件末尾或者出错*/

while(size){

/*每次读取10个字节数据*/

size = read(fd, buf,10);

if( -1 == size) {

/*读取数据出错*/

close(fd);/*关闭文件*/

printf("read file error occurs\n");

/*返回*/

return -1;

}else{

/*读取数据成功*/

if(size >0 ){

/*获得size个字节数据*/

printf("read %d bytes:",size);

/*打印引号*/

printf("\"");

/*将读取的数据打印出来*/

for(i = 0;i

printf("%c",*(buf+i));

}

/*打印引号并换行*/

printf("\"\n");

}else{

printf("reach the end of file\n");

}

}

}

return 0;

}

[[email protected] 03]# ./ex03-read-01

Open file test.txt success,fd:3

read 10 bytes:"aaaaaaaaaa"

read 10 bytes:"aaaaaaaaaa"

read 10 bytes:"aaaaaaaaaa"

read 5 bytes:"aaaa

"

reach the end of file

-----write

[[email protected] 03]# cat ex03-write-01.c

/*文件ex03-write-01.c,

O_CREAT和O_EXCL的使用*/

#include

#include

#include

#include

int main(void)

{

int fd = -1,i;

ssize_t size = -1;

int input = 0;

/*存放数据的缓冲区*/

char buf[]="quick brown fox jumps over the lazy dog";

char filename[] = "test.txt";

/*打开文件,如果文件不存在,则报错*/

fd = open(filename,O_RDWR|O_TRUNC);

if(-1 == fd){

/*文件已经存在*/

printf("Open file %s failure,fd:%d\n",filename,fd);

}       else    {

/*文件不存在,创建并打开*/

printf("Open file %s success,fd:%d\n",filename,fd);

}

/*将数据写入到文件test.txt中*/

size = write(fd, buf,strlen(buf));

printf("write %d bytes to file %s\n",size,filename);

/*关闭文件*/

close(fd);

return 0;

}

[[email protected] 03]# cat text.txt

cat: text.txt: No such file or directory

[[email protected] 03]# cat test.txt

quick brown fox jumps over the lazy dog

原文:http://blog.csdn.net/luozhonghua2014/article/details/38356899

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值