目的:Coin0.bin Coin1.bin Coin2.bin Coin3.bin … Coin21.bin 按文件名排序
1.C#实现
class Program
{
public static int cmp(string name)
{
int length = name.IndexOf(".bin") - name.IndexOf("Coin") - 4;
string str_crap = name.Substring(name.IndexOf("Coin") + 4, length);
return Convert.ToInt32(str_crap);
}
static void Main(string[] args)
{
string Folder = "";\\文件地址
DirectoryInfo theFolder = new DirectoryInfo(Folder);
FileInfo[] fileInfo = theFolder.GetFiles("*.bin");//文件后缀
List<string> fileList = new List<string>();
foreach (var item in fileInfo)
{
//获取文件名
fileList.Add(item.FullName);
}
fileList = fileList.OrderBy(o => cmp(o)).ToList();
foreach (var i in fileList)
{
Console.WriteLine(i);
}
}
}
2.C++ 实现
#include <io.h>
#include <fstream>
#include <string>
#include <vector>
#include <iostream>
#include<algorithm>
#include<functional>
using namespace std;
int findIndex(string a, string b, string c)
{
int index_f, index_l;
int index_gap;
index_f = a.find(b) + 4;
index_l = a.find(c);
index_gap = index_l - index_f;
return atoi((a.substr(index_f, index_gap)).c_str());
}
int cmp(string a, string b)
{
int c, d;
c = findIndex(a, "Coin", ".bin");
d = findIndex(b, "Coin", ".bin");
return c < d;
}
void GetAllFormatFiles(string path, vector<string>& files, string format)//vector是一个能够存放任意类型的动态数组
{
//文件句柄
long hFile = 0;
//文件信息
struct _finddata_t fileinfo;//文件结构体
string p;
if ((hFile = _findfirst(p.assign(path).append("\\*" + format).c_str(), &fileinfo)) != -1)
{
do
{
if (strcmp(fileinfo.name, ".") != 0 && strcmp(fileinfo.name, "..") != 0)
files.push_back(p.assign(path).append("\\").append(fileinfo.name)); //压入
} while (_findnext(hFile, &fileinfo) == 0);
_findclose(hFile);
}
}
int main()
{
string filePath = "";//地址
string format = ".bin";//文件后缀
vector<string> files;//参数存放文件名称
GetAllFormatFiles(filePath, files, format);
sort(files.begin(), files.end(), cmp);//按文件名称从小到大排序
int size = files.size();//向量大小
for (int i = 0; i < size; i++)
{
cout << files[i] << endl;
}
}
3.python实现
from struct import *
import binascii
import os.path,time
import sys
def indexOut(str1):
pos_f = str1.index('Coin') + 4
pos_l = str1.index('.bin')
str2 = str1[pos_f:pos_l]
i = int(str2)
return i
def getFileList(path,endStr):
#'''获取指定目录下,指定后缀的文件列表'''
r_list = []
f_list = os.listdir(path) #获取目录列表
for i in f_list:
# 分离文件名和后缀名,过滤掉工具脚本
file_endStr = os.path.splitext(i)[1]#os.path.splitext('book.txt') ('book', '.txt')
# 判断是否是目录
if file_endStr == endStr:
r_list.append(path + '/' + i)
r_list.sort(key=lambda x:indexOut(x))
return r_list
list = getFileList("",".bin")//地址 文件后缀
file = open(list[2], 'rb')
print(file)