write()和read()的用法,以及结构体(struct)的使用能让文件的读写操作更加便利,尤其是在有选择性的打印出信息时,能够有效存储数据,并且能顺利打印出来。

write():往文件写;read():读文件的内容。

函数API:

        头文件:#include <unistd.h>

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

       fd:打开文件返回的文件标识符。

       buf:存储所要读取的内容或写入的内容。

       count:读取或写入的多少个字节数。

下面直接用代码展示:

往文件写入:

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

int main()
{
   char Buf[128];
   int fd;
   fd=open("./test1",O_RDWR);
   memset(Buf,0,sizeof(Buf));
   strcpy(Buf,"hello How are you?");
   write(fd,Buf,strlen(Buf));
   close(fd);
   return 0;
}
~       

向文件读取:

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

int main()
{
   char readBuf[128];
   int fd;
   int n_read;
   fd=open("./test1",O_RDWR);
   memset(readBuf,0,sizeof(readBuf));
   n_read=read(fd,readBuf,sizeof(readBuf));
   printf("n_read:%d,readBuf:%s\n",n_read,readBuf);
   close(fd);
   return 0;
}
~      

运行结果:

n_read:19,readBuf:hello How are you?

       当我们在学习文件读写操作时,我们刚开始应该直接用指针或数组来定义保存的读写的内容,但我们不能有选择打印出我们想要的。当我们想让程序有选择的打印出结果,比如只打印出"hello",这时我们可以用结构体。

下面直接用代码展示:

往文件写入:

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

struct Msg
{
   char data[28];
   char second[28];

}msg;

int main()
{
   int fd;
   fd=open("./test1",O_RDWR);
   memset(&msg,0,sizeof(msg));
   strcpy(msg.data,"hello");
   strcpy(msg.second,"How are you?");
   write(fd,&msg,sizeof(msg));
   close(fd);
   return 0;
}

向文件读取:

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


struct Msg
{
    char data[28];
    char second[28];
}msg;

int main()
{
   int n_read;
   int fd;
   fd=open("./test1",O_RDWR);
   n_read=read(fd,&msg,sizeof(msg));
   printf("n_read:%d,data: %s ,second:%s \n",n_read,msg.data,msg.second);
   close(fd);
   return 0;
}
~    

运行结果:

n_read:56,data: hello ,second:How are you?

    注:如write()用数组或指针来保存写入内容,read()也要用数组或指针来保存读取的内容,

如果write()用结构体来保存写入内容,read()也要用结构体来保存读取的内容,如果read()要用数组或指针来保存读取的内容,可能不会达到你想要的理想结果,自己可以试试。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值