C++找文件夹中,最长的名字有多长

    科技2025-07-26  7

    // TestForOnlyC++.cpp : 定义控制台应用程序的入口点。 // #include "stdafx.h" #include <fstream> #include <iostream> #include<list> #include <string> #include <sstream> #include <vector> #include<io.h> using namespace std; typedef std::vector<std::string> StringList; /* 分割字符串 */ StringList splitstr(const std::string& str, char tag) { StringList li; std::string subStr; //遍历字符串,同时将i位置的字符放入到子串中,当遇到tag(需要切割的字符时)完成一次切割 //遍历结束之后即可得到切割后的字符串数组 for (size_t i = 0; i < str.length(); i++) { if (tag == str[i]) //完成一次切割 { if (!subStr.empty()) { li.push_back(subStr); subStr.clear(); } } else //将i位置的字符放入子串 { subStr.push_back(str[i]); } } if (!subStr.empty()) //剩余的子串作为最后的子字符串 { li.push_back(subStr); } return li; } void getAllFiles(string path, vector<string>& files) { //文件句柄 long hFile = 0; //文件信息 struct _finddata_t fileinfo; //很少用的文件信息读取结构 string p; //string类很有意思的一个赋值函数:assign(),有很多重载版本 if ((hFile = _findfirst(p.assign(path).append("\\*").c_str(), &fileinfo)) != -1) { do { if ((fileinfo.attrib & _A_SUBDIR)) //判断是否为文件夹 { if (strcmp(fileinfo.name, ".") != 0 && strcmp(fileinfo.name, "..") != 0) { files.push_back(p.assign(path).append("/").append(fileinfo.name));//保存文件夹名字 getAllFiles(p.assign(path).append("/").append(fileinfo.name), files);//递归当前文件夹 } } else //文件处理 { files.push_back(p.assign(path).append("/").append(fileinfo.name));//文件名 } } while (_findnext(hFile, &fileinfo) == 0); //寻找下一个,成功返回0,否则-1 _findclose(hFile); } } //测试 int main() { string DATA_DIR = "D:/WWY/ForMP/imgs"; vector<string> files; //测试 char * DistAll = "AllFiles.txt"; getAllFiles(DATA_DIR, files);//所有文件与文件夹的路径都输出 //ofstream ofn(DistAll); //输出文件流 int size = files.size(); int FaiNum = 0; //ofn << size << endl; cout << size << endl; int Max = 0; int k = 0; for (int i = 0; i<size; i++) { vector<string> test; //cout << k << endl; test = splitstr(files[i], '_'); test[3] = test[3].substr(0, test[3].length()-4); //ofn << files[i] << endl; //cout << test[2] << endl; if (test[3].length() > Max) { Max=test[3].length(); cout <<"第"<<i<<" 次"<< "max=" << Max << endl; //k++; } } //cout << "max="<<Max << endl; //ofn.close(); return 0; }
    Processed: 0.009, SQL: 8