1. 程式人生 > >linux資料夾遍歷字串處理等基礎功能函式

linux資料夾遍歷字串處理等基礎功能函式

/*************************************************************************
	> File Name: filenameio.h
	> Author: lcmf
	> Mail: [email protected] 
	> Created Time: 2018年03月12日 星期一 14時31分22秒
 ************************************************************************/

#include<iostream>
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <sys/time.h>
#include <stdlib.h>
#include <string.h>
//#include <io.h>
#include <cstring>
#include <dirent.h>
#include <fcntl.h>

#include "filenameio.h"

using namespace std;

//清空資料夾
bool removeAllFile(char *strDir)
{
	 DIR *dp;  
	 struct dirent *entry;  
	 struct stat statbuf;  
     if ((dp = opendir(strDir)) == NULL)  
	 {  
	       fprintf(stderr, "cannot open directory: %s\n", strDir);  
	          return -1;  
	 }  
	 chdir (strDir);  
	 while ((entry = readdir(dp)) != NULL)  
	 {  
	     lstat(entry->d_name, &statbuf);  
	     if (S_ISREG(statbuf.st_mode))  
	     {  
	         remove(entry->d_name);  
	     }  
	 }  
	 return 0;  
}

//剪下檔案
bool CutFile(std::string strSrc, std::string strDis)
{
	FILE *in, *out;
	char ch ;
	if ((in = fopen(strSrc.c_str(),"r")) == NULL)
	{
		printf("canot find the in.txt file!\n");
		return false;
	}
	if ((out = fopen(strDis.c_str(),"w"))==NULL)
	{
		printf("canot find the out.txt file!\n");
		return false;
	}
	ch = fgetc(in);
	while (ch!=EOF)
	{
		fputc(ch,out);
		//putchar(ch); //是in.txt 的內容顯示在dos視窗 下
		ch = fgetc(in);
	}
	fclose(in); // 關閉檔案
	fclose(out);

	remove(strSrc.c_str());
}


//獲取當前執行程式路徑
size_t GetCurrentExePath( char* processdir,char* processname, size_t len)  
{  
       char* path_end;  
       if(readlink("/proc/self/exe", processdir,len) <=0)  
               return -1;  
       path_end = strrchr(processdir,  '/');  
       if(path_end == NULL)  
              return -1;  
       ++path_end;  
       strcpy(processname, path_end);  
       *path_end = '\0';  
       return (size_t)(path_end - processdir);  
} 

//獲取檔案的最後修改時間
void GetFileLastModifyTime(char *strPath,int *size,long *modify_time)
{
	FILE * fp;
	int fd;
	struct stat buf;
	fp=fopen(strPath,"r"); //C.zip in current directory, I use it as a test
	fd=fileno(fp);
	fstat(fd, &buf);
	
	*size = buf.st_size; //get file size (byte)
	*modify_time = buf.st_mtime; //latest modification time (seconds passed from 01/01/00:00:00 1970 UTC)
	fclose(fp);
	fp = NULL;
}


//根據時間在某個資料夾下建立資料夾,並返回資料夾名稱
char* CreateDirectoryByTime(char *chPath)
{
	return NULL;
}


//根據檔名稱建立資料夾,返回值為0表示建立成功,返回1表示資料夾已存在,返回-1表示建立失敗位置原因
int createDirectory(const char* strPath)
{
	int nCreate;
	nCreate=mkdir(strPath, S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);
	if(!nCreate)
		cout<<"create success"<< strPath <<endl;
	else
		cout<<"create path failed"<<endl;
	return nCreate;
}


//建立深度資料夾
int safeCreateDirectory(char* strPath)
{
	//依次獲取路徑中的/或者\並建立資料夾
	char *chPath;
	chPath = (char*)malloc(1024);
	strcpy(chPath, strPath);
	char *p = (char*)malloc(1024);
	while(1)
	{
		p = strchr(chPath, '\\');
		if(p != NULL)
		{
			cout << p << endl;

			unsigned char tmp = (unsigned char)(strchr(chPath, '\\') - chPath);  
			char* pre = (tmp > 0)?strndup(chPath, tmp):strdup(chPath);

			createDirectory(pre);

			chdir(pre);

			int size = strlen(p);
			
			cout << size << endl;

			if(size == 1)
				break;

			cout << size << endl;

			strcpy(chPath, p + 1);
			cout << chPath << endl;
			cout << "------------------------------------" << endl;
			free(pre);
		}
		else
		{
			break;
			//return -1;
		}
	}

	free(p);
	free(chPath);
	return 0;
}


//獲取當前系統時間
int GetCurrentTime()
{
	time_t now;
	time(&now);
	return now;
}


//獲取當前時間具體到小時
int GetCurrentHour(char* strCurrent)
{
	timespec time;
	clock_gettime(CLOCK_REALTIME, &time); //獲取相對於1970到現在的秒數
	tm nowTime;
	localtime_r(&time.tv_sec, &nowTime);
//	char current[1024];
//	sprintf(current, "%04d%02d%02d%02d:%02d:%02d", nowTime.tm_year + 1900, nowTime.tm_mon, nowTime.tm_mday, nowTime.tm_hour, nowTime.tm_min, nowTime.tm_sec);
	sprintf(strCurrent, "%04d%02d%02d%02d", nowTime.tm_year + 1900, nowTime.tm_mon, nowTime.tm_mday, nowTime.tm_hour);

//	cout << strCurrent << endl;

	return 0;
}

//遍歷資料夾
void ReverseDirctory(const char* strPath, std::vector<std::string> & arrJsonFilePath)
{
#if 0
	intptr_t handle;
    _finddata_t findData;
	handle = _findfirst(dir, &findData);    // 查詢目錄中的第一個檔案
	if (handle == -1)
	{
	       cout << "Failed to find first file!\n";
	       return;
	}
	
	do
	{
	      if (findData.attrib & _A_SUBDIR && strcmp(findData.name, ".") == 0 && strcmp(findData.name, "..") == 0)    // 是否是子目錄並且不為"."或".."
			  cout << findData.name << "\t<dir>\n";
		  else
		      cout << findData.name << "\t" << findData.size << endl;
	} while (_findnext(handle, &findData) == 0);    // 查詢目錄中的下一個檔案
				
	cout << "Done!\n";
	_findclose(handle);    // 關閉搜尋控制代碼
#endif
}

void scanDir(const char *dir,std::vector<std::string>& arrJsonPath, int depth, bool bDirOrFile)
{
	DIR *dp;                      // 定義子目錄流指標  
	struct dirent *entry;         // 定義dirent結構指標儲存後續目錄  
	struct stat statbuf;          // 定義statbuf結構儲存檔案屬性  
	if((dp = opendir(dir)) == NULL) // 開啟目錄,獲取子目錄流指標,判斷操作是否成功  
	{  
	     puts("can't open dir.");  
	     return;  
	}  
	chdir (dir);                     // 切換到當前目錄  
	while((entry = readdir(dp)) != NULL)  // 獲取下一級目錄資訊,如果未否則迴圈  
	{  
	     lstat(entry->d_name, &statbuf); // 獲取下一級成員屬性  
	     if(S_IFDIR &statbuf.st_mode)    // 判斷下一級成員是否是目錄  
	     {  
	          if (strcmp(".", entry->d_name) == 0 || strcmp("..", entry->d_name) == 0)  
	              continue;  
	          printf("%*s%s/\n", depth, "", entry->d_name);  // 輸出目錄名稱  
	     //     scanDir(entry->d_name, depth+4);              // 遞迴呼叫自身,掃描下一級目錄,但是我們只遍歷當前目錄下的所有json檔案
		if(bDirOrFile)
		  	arrJsonPath.push_back(entry->d_name); 
	     }  
	     else  
		 {
			 //printf("%*s%s\n", depth, "", entry->d_name);  // 輸出屬性不是目錄的成員 
			if(!bDirOrFile)
			 	arrJsonPath.push_back(entry->d_name);
		 }
	}  
	chdir("..");                                                  // 回到上級目錄  
	closedir(dp);                                                 // 關閉子目錄流
}


//整數轉string
std::string IntToStr(int num)
{
	char strNum[100];
	sprintf(strNum, "%d", num);
	return string(strNum);
}

//substring
std::string substr(char* str, unsigned int start, unsigned int end)
{
	unsigned n = end - start;
	char stbuf[256];
	strncpy(stbuf, str + start, n);
	stbuf[n] = 0;
	return (std::string)stbuf;
}

/*
	函式名稱:SplitWords(char* strSrc, std::vector<std::string> & arrWords);
	函式作用:分割字串
*/
int SplitWords(char* strSrc, std::vector<std::string> & arrStr, char chStr)
{
	unsigned int index = 0, len = 0, subIndex = 0, strlength = 0;
	char *tmpSrc = strSrc;
	while (*tmpSrc != '\0')
	{
		strlength++;
		tmpSrc++;
	}
	tmpSrc = strSrc;
	strlength++;
	while(strlength--)
	{
		index++;
		subIndex++;
		if (*tmpSrc == chStr)
		{
			if (subIndex == 1)
			{
				index = 0;
				tmpSrc++;
				continue;
			}		
			if (index == subIndex)
			{
				std::string sr/* = (char*)malloc(index)*/;
				sr = substr(strSrc, 0, index - 1);
				arrStr.push_back(sr);
				index = 0;
				//free(sr);
			}	
			else
			{
				if (subIndex - index == subIndex - 1)
				{
					index = 0;
					tmpSrc++;
					continue;
				}
					
				std::string sr/* = (char*)malloc(subIndex - index)*/;
				sr = substr(strSrc, subIndex - index, subIndex - 1);
				arrStr.push_back(sr);
				index = 0;
				//free(sr);
			}		
		}
		else if(index != 0 && subIndex != 0 && *tmpSrc == '\0')
		{
			string sr/* = (char*)malloc(subIndex - index)*/;
			sr = substr(strSrc, subIndex - index, subIndex - 1);
			if (sr == "")
				return arrStr.size();
			arrStr.push_back(sr);
			index = 0;
			//free(sr);
			return arrStr.size();
		}
		tmpSrc++;
	}
	return arrStr.size();
}