1 #include <stdio.h> 2 #include <iostream> 3 #include <fstream> 4 #include <sstream> 5 #include <streambuf> 6 #include <string> 7 #include <io.h> 8 9 using namespace std; 10 11 int string_replace(std::string& buf, const std::string & src, const std::string & dest) 12 { 13 int pos = 0; 14 int src_len = src.size(); 15 int dest_len = dest.size(); 16 int replace_count = 0; 17 18 while(pos != string::npos) 19 { 20 if((pos = buf.find(src, pos)) > 0) 21 buf.replace(pos, src_len, dest), replace_count++; 22 } 23 24 return replace_count; 25 } 26 27 int main(int argc, char* argv[]) 28 { 29 _finddata_t fd; 30 31 char srcStr[] = "oooooooooooooooooooooooooooooo"; 32 char destStr[] = "xxxxxxxxxxxxxxxxxxxxxxxxxxx"; 33 34 35 long pf = _findfirst("*.cpp",&fd); 36 do 37 { 38 if ((fd.attrib & _A_RDONLY) == 0) // ignore read-only file 39 { 40 // read all from source file 41 ifstream inf(fd.name); 42 std::stringstream filebuf; 43 filebuf << inf.rdbuf(); 44 std::string buf(filebuf.str()); 45 inf.close(); 46 47 // replace string and recover orignal file 48 if (string_replace(buf, std::string(srcStr), string(destStr))) 49 { 50 char newName[128]; 51 memset(newName, 0, 128); 52 sprintf(newName, "%s.bak", fd.name); 53 ofstream newInf; 54 newInf.open(newName, ios::out); 55 newInf << buf; 56 newInf.close(); 57 58 char cmd[100]; 59 sprintf(cmd, "move /Y %s %s", newName, fd.name); 60 system(cmd); 61 } 62 63 } // loop one file 64 }while (!_findnext(pf,&fd)); 65 66 _findclose(pf); 67 68 return 0; 69 }
遍历一个文件夹下是所有类型文件,替换字符串。
时间: 2024-10-11 04:22:46