1.系统调用 - 创建
int creat(const char * filename,mode_t mode)
filename:要创建的文件名(包含路径,缺省为当前路径)
mode:创建模式
常见创建模式:
S_IRUSR 可读
S_IWUSR 可写
S_IXUSR 可执行
S_IRWXU 可读、可写、可执行
使用数字来便是文件的访问权限:
可执行 -> 1
可写 -> 2
可读 -> 4
可读可写 -> 6
无任何权限 ->0
在Linux系统中,所有打开的文件都对应一个文件描述符。文件描述符本质是一个非负整数。
2.系统调用 - 打开
int open(const char * pathname,int flags)
int open(const char * pathname,int flags,mode_t mode)
pathname :要打开的文件名(包含路径,缺省为当前路径)
flags :打开标志
常见的打开标志:
O_RDONLY 只读打开
O_WEONLY 只写打开
O_RDWR 读写打开
O_APPEND 追加打开
O_CREAT 创建一个文件
O_NOBLOCK 非阻塞方式打开
如果视同O_CREAT标志 ,则使用int open(const char * pathname,int flags,mode_t mode)
mode 文件访问权限
#include <fcntl.h>
#include <sys/stat.h>
#include <stdio.h>
int main()
{
int fd = open("hello.c", O_RDONLY);
if(fd > 0)
{
printf("open success\n");
printf("fd is %d\n", fd);
}
else
{
printf("file open failed\n");
}
}
3.系统调用 - 关闭
int close(int fd)
fd 文件描述符
4.系统调用 - 读
int read(int fd,const void *buf,size_t length)
功能:
从文件描述符fd所指的文件中读取length个字节到buf所指向的缓冲区中,返回值是实际读取的字节数。
///一次读取实例
#include <fcntl.h>
#include <sys/stat.h>
#include <stdio.h>
int main()
{
int fd = open("hello.c", O_RDONLY);
if(fd > 0)
{
char buf[1000] = { 0 };
int ret = read(fd, buf, sizeof(buf));
printf("ret is %d\n", ret);
printf("%s", buf);
}
}
///分批次读取实例
#include <fcntl.h>
#include <sys/stat.h>
#include <stdio.h>
#include <memory.h>
int main()
{
int fd = open("hello.c", O_RDONLY);
if(fd > 0)
{
char buf[100] = { 0 };
while(read(fd, buf, sizeof(buf)) > 0)
{
printf("%s", buf);
memset(buf, 0, sizeof(buf));
}
}
}
5.系统调用 - 写
int write(int fd,const void *buf,size_t length)
功能:把length哥字节从buf所指向的缓冲区中写到文件描述符fd所指向的文件,返回值是实际写入的字节数
#include <fcntl.h>
#include <stdio.h>
int main()
{
int a[9] = {11, 12,13, 5, 5, 5, 5, 5, 5};
int b[10] = { 0 };
int fd;
int ret;
fd = open("ccc", O_RDWR | O_CREAT, 0666);
if(fd > 0)
{
ret = write(fd, a, sizeof(a));
printf("ret is %d\n", ret);
close(fd);
}
fd = open("ccc", O_RDONLY);
if(fd > 0)
{
int i;
ret = read(fd, b, sizeof(b));
printf("read ret is %d\n", ret);
for(i = 0; i < 10; i++)
{
printf("%d,", b[i]);
}
printf("\n");
}
}
6.系统调用 - 定位
int lseek(int fd,offset_t offset,int whence)
功能:
将文件读写指针相对whence移动offset个字节。操作成功,返回文件指针相对于文件头的位置
whence可使用下述值:
SEEK_SET:相对文件开头
SEEK_CUR:相对文件对鞋指针的当前位置
SEEK_END:相对文件末尾
offset可取负值,表示向前移动。
如 lseek(fd,-5,SEEK_CUR)
表示可将文件指针相对当前文职向前移动5个字节。
7.系统调用 - 访问判断
有时候我们需要判断文件是否可以进行某种操作,这时可以用access函数。
int access(const char * pathname,int mode)
pathname:文件名
mode:要判断的访问权限,可以取以下值或者组合。
R_OK:文件可读
W_OK:文件可写
X_OK:文件可执行
F_OK:文件存在
返回值:成功返回“0”,否则返回“-1”
8.系统调用 - 获取文件属性
stat(char *file_name, struct stat *buf);
file_name :文件名或目录名
buf : 保存文件属性
#include <stdio.h>
#include <sys/stat.h>
#include <unistd.h>
int main()
{
struct stat s;
int ret = stat("hello.c", &s);
if(ret == 0)
{
printf("size is %d\n", s.st_size);
printf("%s\n", ctime(&(s.st_mtime)));
}
}