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()要用数组或指针来保存读取的内容,可能不会达到你想要的理想结果,自己可以试试。