常用命名
du
作用:显示指定目录或文件所占磁盘空间大小。
 示例:
- du -h
 以K,M,G为单位自动适配显示
lx@lx-virtual-machine:~/test/video$ du -h
1.2G	
- du -m
 指定以1MB为单位显示
lx@lx-virtual-machine:~/test/video$ du -m
1214	
- du -a
lx@lx-virtual-machine:~/test/video$ du -a
24	./word_1.docx
176	./pdf_1.pdf
117984	./video_8.mp4
117984	./video_9.mp4
176	./pdf_2.pdf
117984	./video_7.mp4
104084	./video_baduanjin_2.mp4
156	./pdf_3.pdf
117984	./video_4.mp4
104084	./video_baduanjin_3.mp4
104084	./video_baduanjin_4.mp4
104084	./video_baduanjin_1.mp4
117984	./video_2.mp4
117980	./video_3.mp4
117984	./video_1.mp4
1242756	.
文件系统
文件属性结构 struct stat
函数原型
int stat(const char *path, struct stat *buf);
int lstat(const char *path, struct stat *buf);
- 参数:
 path:文件路径;buf:struct stat的指针。
- 返回值
 0:成功;
 EBADF:文件描述词无效
 EFAULT:地址空间不可访问
 ELOOP:遍历路径时遇到太多的符号连接
 ENAMETOOLONG:文件路径名太长
 ENOENT:路径名的部分组件不存在,或路径名是空字串
 ENOMEM:内存不足
 ENOTDIR:路径名的部分组件不是目录
- 区别:
 stat:没有处理软链接的能力。如果文件是符号链接,也只能返回链接指向文件的属性;
 lstat:如果文件是符号链接,则返回符号链接的内容。
- 结构体信息
struct stat {
	mode_t     st_mode;       //文件对应的模式,文件,目录等
    ino_t      st_ino;       //inode节点号
    dev_t      st_dev;        //设备号码
    dev_t      st_rdev;       //特殊设备号码
    nlink_t    st_nlink;      //文件的连接数
    uid_t      st_uid;        //文件所有者
    gid_t      st_gid;        //文件所有者对应的组
    off_t      st_size;       //普通文件,对应的文件字节数
    time_t     st_atime;      //文件最后被访问的时间
    time_t     st_mtime;      //文件内容最后被修改的时间
    time_t     st_ctime;      //文件状态改变时间
    blksize_t st_blksize;    //文件内容对应的块大小
    blkcnt_t   st_blocks;     //伟建内容对应的块数量
};
获取指定目录所占磁盘空间大小(C++代码实现)
实现方式:借助Linux du命名获取返回内容,并提取数据信息。
 .hpp
#pragma once
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <string>
#include <cstring>
#include <dirent.h>
using namespace std;
class FileProcess
{
public:
	FileProcess() {};
	~FileProcess() {};
	
	uint64_t getDirectorySize(string path)
	{
		string cmd;
		cmd = "du -m " + path;
		FILE* fp = NULL;
		char result[1024] = { 0 };
		char buf[1024] = { 0 };
		if ((fp = popen(cmd.c_str(), "r")) == NULL) {
			printf("popen error!\n");
			return -1;
		}
		while (fgets(buf, sizeof(buf), fp)) {
			strcat(result, buf);
		}
		pclose(fp);
		printf("result: %s\n", result);
		return (uint64_t)atol(string(result).substr(0, string(result).find(' ')).c_str());
	}
	
private:
};
.cpp
void custom_file_process_task()
{
	FileProcess fileProcess;
	string path = "/home/lx/test/video";
	while (1)
	{
		cout << "i am custom_file_process_task" << endl;
		
		uint64_t size = fileProcess.getDirectorySize(path);
		cout << "size: " << size << endl;
		sleep(5);
	}
}
测试结果
 



















