遍历文件的算法,有没有大神可以优化1下的
遍历文件的算法,有没有大神可以优化一下的
自己写的一个遍历文件夹及子文件夹下所有文件 的代码,不想使用全局变量,我的想法是写成:
全局变量如果函数多次调用后,不知道值已经变成什么了,新人水平不高,不知道该如何才能优化,主要就是
filesearch()如果重复调用自己的话,自己所声明的变量就会被覆盖(说法可能不准确)
如何才能vector<ff> v不是全局变量,同时又不被函数调用自己时覆盖?
------解决方案--------------------
------解决方案--------------------
自己写的一个遍历文件夹及子文件夹下所有文件 的代码,不想使用全局变量,我的想法是写成:
vector<ff> filesearch(char newpath[_MAX_PATH])的形式,用函数返回值的形式来取得遍历后的内容
{
vector<ff> v;
///···///
return v;
}
全局变量如果函数多次调用后,不知道值已经变成什么了,新人水平不高,不知道该如何才能优化,主要就是
filesearch()如果重复调用自己的话,自己所声明的变量就会被覆盖(说法可能不准确)
如何才能vector<ff> v不是全局变量,同时又不被函数调用自己时覆盖?
#include <vector>
#include <algorithm>
#include <stdio.h>
#include <io.h>
#include <windows.h>
#include <stdlib.h>
using namespace std;
typedef struct ff
{
char p[_MAX_PATH]; ///完整路径
char n[_MAX_FNAME]; ///文件名
};
vector<ff> v;
void filesearch(char newpath[_MAX_PATH])
{
struct _finddata_t fd;
int handle,done=0;
char path[_MAX_PATH];
strcpy(path,newpath);
strcat(path,"\\*.*");
if(!(handle=_findfirst(path,&fd)))
{
return ;
}
while(!(done=_findnext(handle,&fd)))
{
if(strcmp(fd.name,".")==0 || strcmp(fd.name,"..")==0)
{
continue;
}
if(fd.attrib==_A_SUBDIR)
{
char t[_MAX_PATH];
strcpy(t,newpath);
strcat(t,"\\");
strcat(t,fd.name);
filesearch(t);
continue;
}
else
{
ff f;
char t[_MAX_PATH];
strcpy(t,newpath);
strcat(t,"\\");
strcat(t,fd.name);
strcpy(f.p,t);
strcpy(f.n,fd.name);
v.push_back(f);
}
}
_findclose(handle);
}
int main()
{
FILE *in;
in=fopen("1.txt","w");
filesearch("f:\\11");
for(vector<ff>::size_type i=0;i<v.size();i++)
{
fprintf(in,"%s\n",v[i].p);
}
fclose(in);
system("start 1.txt");
return 0;
}
------解决方案--------------------
void filesearch(char newpath[_MAX_PATH], vector<ff> &v)
{
}
------解决方案--------------------
#include <vector>
#include <algorithm>
#include <stdio.h>
#include <io.h>
#include <iostream>
#include <stdlib.h>
using namespace std;
typedef struct
{
char p[_MAX_PATH]; ///完整路径
char n[_MAX_FNAME]; ///文件名
}ff;
void filesearch(char newpath[_MAX_PATH]/*in*/, vector<ff>& fvec )
{
struct _finddata_t fd;
int handle, done = 0;
char path[_MAX_PATH];
strcpy_s(path,_MAX_PATH, newpath);
strcat_s(path,_MAX_PATH, "\\*.*");
if (!(handle = _findfirst(path, &fd)))
{
fvec.clear();
return;
}
while (!(done = _findnext(handle, &fd)))
{
if (strcmp(fd.name, ".") == 0
------解决方案--------------------
strcmp(fd.name, "..") == 0)
{
continue;
}
if (fd.attrib == _A_SUBDIR)
{
char t[_MAX_PATH];
strcpy_s(t,_MAX_PATH, newpath);
strcat_s(t, _MAX_PATH, "\\");
strcat_s(t, _MAX_PATH, fd.name);
filesearch(t, fvec);
continue;
}
else
{
ff f;
char t[_MAX_PATH];
strcpy_s(t, newpath);
strcat_s(t, "\\");
strcat_s(t, fd.name);
strcpy_s(f.p, t);
strcpy_s(f.n, fd.name);
fvec.push_back(f);
}
}
_findclose(handle);
}
int main()
{
vector<ff> fvec;
FILE *in;
fopen_s(&in, "1.txt", "w");
filesearch("f:\\my_proj", fvec);
for (vector<ff>::size_type i = 0; i < fvec.size(); i++)
{
fprintf(in, "%s\n", fvec[i].p);
}
fclose(in);
system("start 1.txt");
}