系统级程序编程:linux系统文件及操作
今天系统级程序设计课程开课了,和我想的并不一样,这门课听老师说偏底层一点。
今天主要是用C语言为工具讲解了在Linux系统下文件的操作。
所用函数:
1.open()
int open(const char *pathname, int flags[,mode_t mode])
/*
参数含义:
*pathname: 文件路径名
flags:文件的访问模式
mode_t mode: 这个参数只有当flags == O_CREATE时才会被使用, 用于设置新文件的权限
open()函数调用成功后会返回一个描述符, 否则返回-1
*/
2.read()
ssize_t read(int fd, viod *buf, size_t count)
/*
参数含义:
fd: 文件的描述符
*buff:读取数据的缓冲区
count:读取数据字节数
*/
3.write()
ssize_t write(int fd, const void *buf, size_t count);
//count:最大输出字节数
4.lseek()
offf_t lseek(int fd, off_t offest, int whence)
/*
参数描述:
fd:文件描述符
offest: 对文件的偏移量进行设置,可正可负,=
whence: 设置偏移量的方法
*/
5.close()
int close(int fd)
//功能描述:关闭文件
案例实现:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
int main(){
int fd = 0;
char filename[20] = "aaa.txt";
fd = open(filename, O_RDWR|O_EXCL|O_TRUNC, S_IRWXG);
if (fd == -1){
perror("file open error.\n");
exit(-1);
}
int len = 0;
char buf[100] = {0};
scanf("%s", buf);
len = strlen(buf);
write(fd, buf, len);
close(fd);
printf("-----------------------\n");
fd = open(filename, O_RDONLY);
if(fd == -1){
perror("file open error.\n");
exit(-1);
}
off_t f_size = 0;
f_size = lseek(fd, 0, SEEK_END);
lseek(fd, 0, SEEK_SET);
while(lseek(fd, 0, SEEK_CUR) != f_size){
read(fd, buf, 1024);
printf("%s\n", buf);
}
close(fd);
return 0;
}
通过这个实例学习,我更加熟练的掌握的文件操作的五个函数,收益匪浅。
OK。