code:1
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
int main()
{
int fd;
char *buf = "chenhaimian come on!";
fd=open("./file1", O_RDWR);
if (fd < 0){
printf("Not Find File1,RDWR fail!\n");
fd=open("./file1", O_RDWR | O_CREAT, 0600);
printf("the start touch a file1\n");
if(fd >0){
printf("Touch File success,OK\n");
}
}
printf("fd=%d\n",fd);
ssize_t wNum = write(fd,buf,strlen(buf));
printf("wNum=%zd\n",wNum);
close(fd);
return 0;
}
运行结果:
CLC@Embed_Learn:~/LinuxLearn/FILE$ ./a.out
Not Find File1,RDWR fail!
the start touch a file1
Touch File success,OK
fd=3
wNum=20
注:
// int open(const char *pathname, int flags);
// int open(const char *pathname, int flags, mode_t mode);
// int creat(const char *pathname, mode_t mode);
// ssize_t write(int fd, const void *buf, size_t count);
// int close(int fd);
pathname:要打开文件名(路径,“.”缺省当前文件的路径)
flags:打开文件的权限 ,如:
O_RDONLY, O_WRONLY, O_RDWR.(只读打开,只写打开,可读可写打开)
可搭配(O_CREAT\O_EXCL\O_APPEND\O_TRUNC)使用:如代码。
- O_CREAT 文件不存在创建
- O_EXCL 和O_CREAT一起使用,则出错。判断文件存不存在。
- O_APPEND 相当于把光标移到了末端
- O_TRUNC 清除文件的内容
mode:一定是在flags中使用了O_CREAT标志,mode记录待创建的文件访问权限。 - open返回值-------文件描述符(索引)
- 像这类型“ssize_t ”没见过得函数类型,可百度看看他的返回值怎么打印,不行可用int代替看是否能编译通过。
code:2
int main()
{
int fd;
int wrByt;
int rdByt;
char *wr_buf = "chenhaimian come on!";
fd=open("./file1", O_RDWR);
if (fd < 0){
printf("Not Find File1,RDWR fail!\n");
fd=open("./file1", O_RDWR | O_CREAT, 0600);
printf("the start touch a file1\n");
if(fd >0){
printf("Touch File success,OK\n");
}
}
wrByt=write(fd,wr_buf,strlen(wr_buf));
if(wrByt > 0){
printf("write %d Byt,%s\n",wrByt,wr_buf);
}
lseek(fd,0,SEEK_SET);//'head'-begin read.offset == 0;
char *rd_buf;
rd_buf=(char *)malloc(sizeof(wrByt));
rdByt=read(fd,rd_buf,wrByt);
printf("read %d Byt,%s\n",rdByt,rd_buf);
lseek(fd,-rdByt,SEEK_END);//'tail'-begin read.offset == -19;
rdByt=read(fd,rd_buf,wrByt);
printf("read %d Byt,%s\n",rdByt,rd_buf);
lseek(fd,-wrByt,SEEK_CUR);//'now site'-begin read.offset == -wtByt;
rdByt=read(fd,rd_buf,wrByt);
printf("read %d Byt,%s\n",rdByt,rd_buf);
close(fd);
return 0;
}
注:
// off_t lseek(int fd, off_t offset, int whence);
whence:文件的位置
- SEEK_SET(头)
The offset is set to offset bytes. - SEEK_CUR(当前位置)
The offset is set to its current location plus offset bytes. - SEEK_END(末尾)
The offset is set to the size of the file plus offset bytes.
off_t offset:文件相对于whence偏移值,具体用法看代码2.
- 对一个文件同时进行读写的时候要注意文件的光标所在的位置。
可以用lseek光标计算文件的大小。