리눅스 환경에서 C ++에서 파일을 삭제
"토크가 싸다, 나에게 코드를 보여!"
#include <cstdio>
#include <string>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <iostream>
#include <vector>
#include <dirent.h>
#include <time.h>
using namespace std;
const long day = 86400;
//获取文件的给更新时间
long get_file_modify_time(string filepath)
{
struct stat filehand;
FILE *fp;
fp = fopen(filepath.c_str(), "r");
int fileid = fileno(fp);
fstat(fileid, &filehand);
fclose(fp);
return filehand.st_mtime;
}
//获取文件夹中的所有文件
void get_files(const string dirname, vector<string> &filelist)
{
if(dirname.empty())
return;
struct stat s;
stat(dirname.c_str(), &s);
if(!S_ISDIR(s.st_mode))
return;
DIR *dirhand = opendir(dirname.c_str());
if(NULL == dirhand){
exit(EXIT_FAILURE);
}
dirent *fp = nullptr;
while((fp = readdir(dirhand)) != nullptr){
if(fp->d_name[0] != '.'){//十分重要的一行(?)
string filename = dirname + "/" + string(fp->d_name);
struct stat filemod;
stat(filename.c_str(), &filemod);
if(S_ISDIR(filemod.st_mode)){
get_files(filename, filelist);
}
else if(S_ISREG(filemod.st_mode)){
filelist.push_back(filename);
}
}
}
closedir(dirhand);
return;
}
bool delete_file(string filepath)
{
return remove(filepath.c_str());
}
bool date_from_now(long now, long modify)
{
int dis = int((1.0 * (now - modify) / day + 0.5));
return dis >= 9;//删除最近更新时间距今超过14天的文件
}
int main()
{
time_t now;
time(&now);//获取当前系统时间
string dir = "/file/cpp";//需要处理的文件夹
vector<string> filelist;
get_files(dir, filelist);//获取文件夹中的所有文件
for(auto i : filelist){
if(date_from_now(now, get_file_modify_time(i))){
cout << i << endl;
if(!delete_file(i)){
cout << "The file named : " << i << " has been deleted." << endl;
}
else{
cout << "Delete Failed!" << endl;
}
}
}
return 0;
}
당신이 리눅스 프로그래밍을 통해 자세히 배울 수없는 경우에, 나는에 대한 자세한 분석 다음에 코드를 이해하지 못하고 있습니다 :
가져 오기 파일이 마지막으로 업데이트 된
해당 코드
//获取文件的给更新时间
long get_file_modify_time(string filepath)
{
struct stat filehand;
FILE *fp;
fp = fopen(filepath.c_str(), "r");
int fileid = fileno(fp);
fstat(fileid, &filehand);
fclose(fp);
return filehand.st_mtime;
}
스탯 데이터 구조 및 파일 작업에 사용 된 코드는 C는 학생들이 작업이 더 잘 알고있는 파일을해야 배웠습니다.
구조체 합계가 해당 구조 및 기능의 개수를 사용하여 파일 저장하는 데이터 구조 정보를 포함 할 수있는
<SYS / types.h> 和 <SYS / stat.h>
우리는 데이터 구조가 파일에 해당하는 얻을 기능 fstat를 파일에 사용할 수있는,fstat(int fid, struct stat *struct_stat)
파일 기술자 인 FID, 고유 한 파일 번호로 이해 될 수있다, 사용 파일 조작 함수에 우리가 가지고있는 번호를 얻을.
첫째로, fopen()
파일 열기 및 파일 포인터를 얻기가 다음 fileno()
파일 디스크립터를 얻었다.
구조체에 대한 통계 속성은 다음과 같습니다 :
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; //伟建内容对应的块数量
};
우리는있는 파일의 가장 최근의 업데이트 시간 얻을 필요 st_mtime
(참고 :이 속성은 초 [GMT] 번호에서 1970 년 1 월 1 일 0시 0분 0초에있다가 시간이 표시).
모든 파일을 가져 오기
해당 코드
//获取文件夹中的所有文件
void get_files(const string dirname, vector<string> &filelist)
{
if(dirname.empty())
return;
struct stat s;
stat(dirname.c_str(), &s);
if(!S_ISDIR(s.st_mode))
return;
DIR *dirhand = opendir(dirname.c_str());
if(NULL == dirhand){
exit(EXIT_FAILURE);
}
dirent *fp = nullptr;
while((fp = readdir(dirhand)) != nullptr){
if(fp->d_name[0] != '.'){//十分重要的一行
string filename = dirname + "/" + string(fp->d_name);
struct stat filemod;
stat(filename.c_str(), &filemod);
if(S_ISDIR(filemod.st_mode)){
get_files(filename, filelist);
}
else if(S_ISREG(filemod.st_mode)){
filelist.push_back(filename);
}
}
}
closedir(dirhand);
return;
}
이 섹션에서 우리는 기능과 치료에 폴더 구조의 일부를 사용, <dirent.h를> 헤더 파일을 도입 할 필요가있다
이 섹션에서 우리는 두 개의 인수의 함수로 전달해야, 파일이 같은 폴더 및 파일 목록을 처리해야 (모든 파일, 여기에 구현 벡터를 저장합니다)
처음에 우리에 의하여 다음 구조체 합계 변수 등을 저장하는 첫 번째 폴더 S_ISDIR()
종료되지 않은 경우,이 폴더 여부를 결정하고, 만약 그렇다면, 우리가 보류 정보 폴더에 DIR 구조를 사용하고자하는 함수.
DIR 값은 그했던 opendir에서 얻은 (숯 *의 FILE_PATH) 기능 폴더 구조의 변수를 정의 할 수있다.
dirent라는 변수 다음은 포함 폴더를 포함한 폴더에서 모든 파일을 통과 할 수 있습니다. 이것은 변수에 dirent가 readdir (DIR * P) 함수의 값으로부터 얻을 수있다.
에 dirent 구조 속성이 저장됩니다
struct dirent
{
long d_ino; /* inode number 索引节点号 */
off_t d_off; /* offset to this dirent 在目录文件中的偏移 */
unsigned short d_reclen; /* length of this d_name 文件名长 */
unsigned char d_type; /* the type of d_name 文件类型 */
char d_name [NAME_MAX+1]; /* file name (null-terminated) 文件名,最长255字符 */
}
여기에서 우리는 메모, 파일 이름 및 파일 경로가 구성 얻을하는 d_name 문자열을 사용해야합니다 폴더에있는 두 디렉토리를 파일의 시작 부분과 ".."파일을, 정력과 인쇄 파일을 "." 당신이 볼 수있는 나무는,이 두 가지가 우리가 때 이송이 두 파일을 제외 할 수 있도록, 현재 디렉토리와 부모 디렉토리를 표시하거나 무한 재귀, 프로그램이 충돌의 원인이됩니다! ! !
S_ISDIR () 함수 외에도 우리는 파일이 보통 파일인지 확인하기 위해 S_ISREG를 () 함수가 사용합니다.
현재 시스템 시간을 가져옵니다
time_t now;
time(&now);//获取当前系统时间
본원에서 사용 시간 () 함수 <time.h> 라이브러리 포함
파일 삭제
bool delete_file(string filepath)
{
return remove(filepath.c_str());
}
C ++ 제거 () 함수는 실행 파일을 삭제 사용할 수 있습니다.