linux 目录 读写,Linux C 文件与目录3 文件读写(示例代码)

文件读写

文件读写是指从文件中读出信息或将信息写入到文件中。Linux文件读取可使用read函数来实现的,文件写入可使用write函数来实现。在进行文件写入的操作时,只是在文件的缓冲区中操作,可能没有立即写入到文件中。需要使用sync或fsync函数将缓冲区的数据写入到文件中。

文件写操作:

函数write可以把一个字符串写入到一个已经打开的文件中,这个函数的使用方法如下:

ssize_t  write  (int fd , void *buf , size_t  count);

参数:

fd:已经打开文件的文件编号。

buf:需要写入的字符串。

count:一个整数型,需要写入的字符个数。表示需要写入内容的字节的数目。

返回值:

如果写入成功,write函数会返回实际写入的字节数。发生错误时则返回-1,可以用errno来捕获发生的错误。

[[email protected] exercise]$ cat write.c

#include

#include

#include

#include

#include

#include

#include

int main(void)

{

int fd ;

char path[] = "txt1.txt";

char s[]="hello ...";

extern int errno;

fd = open(path , O_WRONLY|O_CREAT|O_TRUNC , 0766);

if(fd != -1)

{

printf("opened file %s .\n" , path);

}

else

{

printf("can‘t open file %s.\n" , path);

printf("errno: %d\n" , errno);                          //打印错误编号

printf("ERR : %s\n" , strerror(errno));             //打印错误编号对应的信息。

}

write(fd , s , sizeof(s));

close(fd);

printf("Done\n");

return 0;

}

[[email protected] exercise]$ ./write

opened file txt1.txt .

Done

读取文件函数read

函数read可以从一个打开的文件中读取字符串。

ssize_t  read(int fd , void *buf , size_t  count);

参数:fd:表示已经打开的文件的编号。

buf:是个空指针,读取的内容会返回到这个指针指向的字符串。

count:表示需要读取的字符的个数。

返回值:返回读取到字符的个数。如果返回值为0,表示已经达到文件末尾或文件中没有内容可读。

fd = open(path , O_RDONLY);

if(fd != -1)

{

printf("opened file %s .\n" , path);

}

else

{

printf("can‘t open file %s.\n" , path);

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

printf("ERR : %s\n" , strerror(errno));

}

if((size = read(fd , str , sizeof(str))) < 0)

{

printf("ERR: %s" , strerror(size));                    //如果有错,通过错误编号打印错误消息。

}

else

{

printf("%s\n" , str);

printf("%d\n" , size);

}

close(fd);

return 0;

}

result:

opened file txt1.txt .

hello ...

10

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值