1. Linux文件操作相关函数(在 man 2(5)中查看函数用处)
stat函数 *****
穿透(追踪)函数 -- 软链接
lstat函数
不穿透(追踪)
access函数
chmod函数
chown函数 用户组ID和用户ID通过etc中passwd来获取;
truncate函数 ***
文件长度 100
第二个参数指定长度为 20
.................. 300 -> 文件被拓展
链接函数
link函数
symlink函数
readlink函数
unlink函数(功能)创建零时文件,当我们将文件关掉之后。创建的文件会自动将文件删掉。
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
int main(void)
{
int fd = open("tempfile", O_CREAT | O_RDWR, 0755);
if(fd == -1)
{
perror("open");
exit(1);
}
int ret = unlink("tempfile");
if(ret == -1)
{
perror("unlink");
exit(1);
}
char buf[512];
write(fd, "hello", 5);
lseek(fd, 0, SEEK_SET);
int len = read(fd, buf, sizeof(buf));
write(STDOUT_FILENO, buf, len);
close(fd);
return 0;
}
filenum.c函数(计算文件目录的大小)
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
int getFileNum(char* root)
{
// 打开目录
DIR* dir = opendir(root);
if(dir == NULL)
{
perror("opendir");
exit(0);
}
// 读目录
int total = 0;
char path[1024] = {0};
struct dirent* ptr = NULL;
while((ptr = readdir(dir)) != NULL)
{
// 跳过 . 和 ..
if(strcmp(ptr->d_name, ".") == 0 || strcmp(ptr->d_name, "..") == 0)
{
continue;
}
// 判断是不是文件
if(ptr->d_type == DT_REG)
{
total ++;
}
// 如果是目录
if(ptr->d_type == DT_DIR)
{
// 递归读目录
sprintf(path, "%s/%s", root, ptr->d_name);
total += getFileNum(path);
}
}
closedir(dir);
return total;
}
int main(int argc, char* argv[])
{
// 读目录, 统计文件个数
int total = getFileNum(argv[1]);
// 打印
printf("%s has file number: %d\n", argv[1], total);
return 0;
}
2. Linux目录操作相关函数
3. fcntl 函数
改变已经打开的文件的属性
打开文件的时候: 只读
修改文件的: 添加追加 O_APPEND
4. dup, dup2函数
复制现有的文件描述符fd=open("a.txt",O_RDWR);
解决gcc编译过程中c99语法报错的问题
~/.bashrc
alias gcc='gcc -std=gnu99'
索引节点inode:保存的其实是实际的数据的一些信息,这些信息称为“元数据”(也就是对文件属性的描述)。
例如:文件大小,设备标识符,用户标识符,用户组标识符,文件模式,扩展属性,文件读取或修改的时间戳,
链接数量,指向存储该内容的磁盘区块的指针,文件分类等等。
( 注意数据分成:元数据+数据本身 )
注意inode怎样生成的:每个inode节点的大小,一般是128字节或256字节。inode节点的总数,在格式化时就给定
(现代OS可以动态变化),一般每2KB就设置一个inode。一般文件系统中很少有文件小于2KB的,所以预定按照2KB分,
一般inode是用不完的。所以inode在文件系统安装的时候会有一个默认数量,后期会根据实际的需要发生变化。
注意inode号:inode号是唯一的,表示不同的文件。其实在Linux内部的时候,访问文件都是通过inode号来进行的,
所谓文件名仅仅是给用户容易使用的。当我们打开一个文件的时候,首先,系统找到这个文件名对应的inode号;然后,
通过inode号,得到inode信息,最后,由inode找到文件数据所在的block,现在可以处理文件数据了。
inode和文件的关系:当创建一个文件的时候,就给文件分配了一个inode。一个inode只对应一个实际文件,
一个文件也会只有一个inode。inodes最大数量就是文件的最大数量。
FILE* fp = open("file");