1.API函数之read函数
ssize_t read(int fd, void *buf, size_t count);
fd指向的文件读取count个字节的数据放到buf里。
成功运行则读了多少个字节就返回了多少个字节,读取错误返回-1。
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
int main()
{
int fd;
char *buf="Hello World";
fd=open("./file1",O_RDWR);
if(fd==-1){
printf("open file1 failed\n");
fd=open("./file1",O_RDWR|O_CREAT,0600);
if(fd>0){
printf("create file1\n");
}
}
printf("open sucess:fd=%d\n",fd);
// ssize_t write(int fd,const void *buf,size_t count);
int n_write=write(fd,buf,strlen(buf));
if(n_write!=-1){
printf("write %d byte to file\n",n_write);
}
close(fd);
fd=open("./file1",O_RDWR);
char *readbuf;
readbuf=(char *)malloc(sizeof(char)*n_write+1);
int n_read=read(fd,readbuf,n_write);
printf("read %d,context:%s\n",n_read,readbuf);
close(fd);
return 0;
}
写入的buf与读取的readbuf空间地址不同。
write和read放在一起会出去读不出来,这是因为write好后光标移到后面了因此读出来的字节为0,可以先关闭文件重新打开文件,这样光标就在第一个也就能读取字节了。也有另外一种方式就是将光标移到第一个字节。
2.API函数之lseek
off_t lseek(int fd, off_t offset, int whence);
通过fd打开需要的文件,在whence,偏移offset个字节。
whence填写:SEEK_SET(光标指向头)/SEEK_CUR(光标指向当前位置)/SEEK_END(光标指向尾)
offset为负数则向光标的左边偏移,否则反之。
如果调用成功返回值为偏移的字节。
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
int main()
{
int fd;
char *buf="HelloWorld";
fd=open("./file1",O_RDWR);
if(fd==-1){
printf("open file1 failed\n");
fd=open("./file1",O_RDWR|O_CREAT,0600);
if(fd>0){
printf("create file1\n");
}
}
printf("open sucess:fd=%d\n",fd);
// ssize_t write(int fd,const void *buf,size_t count);
int n_write=write(fd,buf,strlen(buf));
if(n_write!=-1){
printf("write %d byte to file\n",n_write);
}
// close(fd);
// fd=open("./file1",O_RDWR);
char *readbuf;
readbuf=(char *)malloc(sizeof(char)*n_write+1);
lseek(fd,0,SEEK_SET);
int n_read=read(fd,readbuf,n_write);
printf("read %d,context:%s\n",n_read,readbuf);
close(fd);
return 0;
}
上述代码将光标移到第一个字节前,这样就能read出现要的字符串
int main()
{
int fd;
char *buf="HelloWorld";
fd=open("./file1",O_RDWR);
int filesize=lseek(fd,0,SEEK_END);
printf("file size %d\n",filesize);
close(fd);
return 0;
}
上述代码运行成功则输出了“helloworld”这几个字节的个数。
2.API函数之creat
int creat(const char *pathname, mode_t mode);
pathname:要创建的文件名(包含路径)。
mode:创建的模式;
模式分为4种:
1.S_IRUSR 可读
2.S_IWUSR 可写
3.S_IXUSR 可执行
4.S_IRWXU 可读、可写、可执行
int main()
{
int fd;
fd=creat("./file3",S_IRWXU);
close(fd);
return 0;
}
上述代码创建了file3这个文件夹