最近有一个需求,就是给一个目录,然后把里面所有的文件内容都修改,并修改文件名。
#include "stdafx.h" #undef UNICODE #include <stdio.h> #include <stdlib.h> #include <Windows.h> #include <iostream> #include <fstream> #include <string> #include <vector> using namespace std; void format(char *cfilename, string &newName); void browseFile(char* path) { char pattern[FILENAME_MAX + 1]; sprintf(pattern, "%s\\*.*", path); char fdPath[FILENAME_MAX + 1];//file or document path WIN32_FIND_DATA findFileData; HANDLE hFindFile = FindFirstFile(pattern, &findFileData); if (hFindFile != INVALID_HANDLE_VALUE) { do { if (strcmp(findFileData.cFileName, ".") == 0 || strcmp(findFileData.cFileName, "..") == 0) { continue; } sprintf(fdPath, "%s\\%s", path, findFileData.cFileName); if (findFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { cout<<fdPath<<endl;//对目录做一些操作 browseFile(fdPath);//访问目录下面的内容 } else { string newFileName; cout<<"\t"<<findFileData.cFileName<<endl;//对文件做一些操作 ifstream fin;//#include <fstream> fin.open(fdPath); if(!fin) cout<<"file "<<findFileData.cFileName<<" not exist"<<endl; else { format(fdPath,newFileName); } fin.close(); if (!rename(fdPath, newFileName.c_str()) == 0) perror("rename"); } } while (FindNextFile(hFindFile, &findFileData)); } FindClose(hFindFile); } void format(char *cfilename, string &newFileName) { ifstream fin; string filename(cfilename); fin.open(filename); vector<string> datas; string line; getline(fin,line); fin.clear(); fin.seekg(0); vector<int> vindex; int pos = 0; while(line.npos !=(pos= line.find(" ",pos))) { vindex.push_back(pos++); } string exch = line.substr(vindex[1]+1,vindex[2]-vindex[1] - 1); exch.insert(0,"_"); while(!fin.eof()) { getline(fin,line); if(line=="") continue; vector<int> vindex; int pos = 0; while(line.npos !=(pos= line.find(" ",pos))) { vindex.push_back(pos++); } string sub1 = line.substr(vindex[3]+1,vindex[4]-1-vindex[3]); string sub2 = line.substr(vindex[7]+1,vindex[13]-1-vindex[7]); string sub3 = line.substr(vindex[15]+1,vindex[17]-1-vindex[15]); string sub4 = line.substr(vindex[19]+1,vindex[41]-1-vindex[19]); string r = sub1+" "+sub2+" "+sub3+" "+sub4; datas.push_back(r); } fin.close(); ofstream fout; fout.open(filename,ios::trunc);//打开后清空文件 vector<string>::iterator sitr = datas.begin(); while(sitr != datas.end()) { fout<<*sitr<<endl; ++sitr; } fout.close(); int dotPos = filename.find_last_of("."); newFileName = filename; newFileName.insert(dotPos,exch); } int _tmain(int argc, _TCHAR* argv[]) { browseFile("C:\\Users\\ydu1\\Desktop\\ffff\\file"); return 0; }
原文地址:http://www.cnblogs.com/dy-techblog/p/3853656.html