C++ string::npos,结合find,或者sscanf

本文介绍C++中使用getline进行文件读取的方法,并展示了如何通过字符串操作来解析配置信息,还提供了查找字符串中特定字符位置的示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >



    首先getline

getline(istream &in, string &s)

从输入流读入一行到string s

•功能:
–从输入流中读入字符,存到string变量
–直到出现以下情况为止:
•读入了文件结束标志
•读到一个新行
•达到字符串的最大长度
–如果getline没有读入字符,将返回false,可用于判断文件是否结束
  1. #include<iostream>  
  2. #include<fstream>  
  3. #include<string>  
  4.   
  5. using namespace std;  
  6.   
  7. int main()  
  8. {  
  9.     string buff;  
  10.     ifstream infile;  
  11.     ofstream outfile;  
  12.     cout<<"Input file name: "<<endl;  
  13.     cin>>buff;  
  14.     infile.open(buff.c_str());  
  15.   
  16.     if(!infile)  
  17.         cout<<"error"<<buff<<endl;  
  18.       
  19.     cout<<"Input outfile name: "<<endl;  
  20.     cin>>buff;  
  21.     outfile.open(buff.c_str());  
  22.       
  23.     while(getline(infile, buff))  
  24.         outfile<<buff<<endl;  
  25.   
  26.     infile.close();  
  27.     outfile.close();  
  28.     return 0;  
  29.   
  30. }  
#include<iostream>
#include<fstream>
#include<string>

using namespace std;

int main()
{
	string buff;
	ifstream infile;
	ofstream outfile;
	cout<<"Input file name: "<<endl;
	cin>>buff;
	infile.open(buff.c_str());

	if(!infile)
		cout<<"error"<<buff<<endl;
	
	cout<<"Input outfile name: "<<endl;
	cin>>buff;
	outfile.open(buff.c_str());
	
	while(getline(infile, buff))
		outfile<<buff<<endl;

	infile.close();
	outfile.close();
	return 0;

}


      

http://blog.youkuaiyun.com/stpeace/article/details/13069403

设1.txt文件内容如下:

name = baidu
url = www.baidu.com

 

       看程序:

  1. #include <fstream>  
  2. #include <string>  
  3. #include <iostream>  
  4. using namespace std;  
  5.   
  6. int main()  
  7. {  
  8.     ifstream in("1.txt");  
  9.     string filename;  
  10.     string line;  
  11.     string s;  
  12.     string :: size_type pos;  
  13.   
  14.     if(in) // 有该文件  
  15.     {  
  16.         while (getline (in, line)) // line中不包括每行的换行符  
  17.         {   
  18.             pos = line.find("name");  
  19.             if(pos != string :: npos)  
  20.             {  
  21.                 s = line.substr(pos + strlen("name") + strlen(" = "));  
  22.                 cout << s.c_str() << endl;  
  23.             }  
  24.   
  25.             pos = line.find("url");  
  26.             if(line.find("url") != string :: npos)  
  27.             {  
  28.                 s = line.substr(pos + strlen("url") + strlen(" = "));  
  29.                 cout << s.c_str() << endl;  
  30.             }  
  31.   
  32.         }  
  33.     }  
  34.     else // 没有该文件  
  35.     {  
  36.         cout <<"no such file" << endl;  
  37.     }  
  38.   
  39.     return 0;  
  40. }  
#include <fstream>
#include <string>
#include <iostream>
using namespace std;

int main()
{
	ifstream in("1.txt");
	string filename;
	string line;
	string s;
	string :: size_type pos;

	if(in) // 有该文件
	{
		while (getline (in, line)) // line中不包括每行的换行符
		{ 
			pos = line.find("name");
			if(pos != string :: npos)
			{
				s = line.substr(pos + strlen("name") + strlen(" = "));
				cout << s.c_str() << endl;
			}

			pos = line.find("url");
			if(line.find("url") != string :: npos)
			{
				s = line.substr(pos + strlen("url") + strlen(" = "));
				cout << s.c_str() << endl;
			}

		}
	}
	else // 没有该文件
	{
		cout <<"no such file" << endl;
	}

	return 0;
}

     结果为:

baidu

www.baidu.com

 

    当然也可以用sscanf, 如下:

  1. #include <fstream>  
  2. #include <string>  
  3. #include <iostream>  
  4. using namespace std;  
  5.   
  6. int main()  
  7. {  
  8.     ifstream in("1.txt");  
  9.     string filename;  
  10.     string line;  
  11.     char s1[1024] = {0};  
  12.     char s2[1024] = {0};  
  13.   
  14.     if(in) // 有该文件  
  15.     {  
  16.         while (getline (in, line)) // line中不包括每行的换行符  
  17.         {   
  18.             if(2 == sscanf(line.c_str(), "%s = %s", s1, s2))  
  19.             {  
  20.                 cout << s2 << endl;  
  21.             }  
  22.             else  
  23.             {  
  24.                 return 1;  
  25.             }  
  26.               
  27.         }  
  28.     }  
  29.     else // 没有该文件  
  30.     {  
  31.         cout <<"no such file" << endl;  
  32.     }  
  33.   
  34.     return 0;  
  35. }  



拓展:

查找两个字符串中的公共字符;

返回公共字符的索引;

  1. #include<iostream>  
  2. #include<string>  
  3.   
  4. using namespace std;  
  5.   
  6. int main()  
  7. {  
  8.     string s = "**Gteate Wall**!";  
  9.     string t = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";  
  10.     cout<<"s: "<<s<<endl;  
  11.     cout<<"t: "<<t<<endl;  
  12.   
  13.     int first=s.find_first_of(t);  
  14.   
  15.     if(first == string::npos){  
  16.         cout<<"s中所有字符均不在t中"<<endl;  
  17.     }else {  
  18.         cout<<"s中出现在t中的字符的第一个字符:"<<s[first]<<endl;  
  19.     }  
  20.   
  21.     int last = s.find_last_of(t);  
  22.     if(last == string::npos){  
  23.         cout<<"s中所有字符均不在t中"<<endl;  
  24.         return 1;  
  25.     }else {  
  26.         cout<<"s中出现在t的字符的最后一个字符:"<<s[last]<<endl;  
  27.         return 1;  
  28.     }  
  29.   
  30. }  
<u>#include<iostream>
#include<string>

using namespace std;

int main()
{
	string s = "**Gteate Wall**!";
	string t = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
	cout<<"s: "<<s<<endl;
	cout<<"t: "<<t<<endl;

	int first=s.find_first_of(t);

	if(first == string::npos){
		cout<<"s中所有字符均不在t中"<<endl;
	}else {
		cout<<"s中出现在t中的字符的第一个字符:"<<s[first]<<endl;
	}

	int last = s.find_last_of(t);
	if(last == string::npos){
		cout<<"s中所有字符均不在t中"<<endl;
		return 1;
	}else {
		cout<<"s中出现在t的字符的最后一个字符:"<<s[last]<<endl;
		return 1;
	}

}
</u>

string::npos的一些说明

string::npos 的一些说明

一、定义

std:: string ::npos的定义:

static const size_t npos = -1;

表示 size_t 的最大值( Maximum value for size_t ) ,如果对 -1 表示size_t的最大值有疑问可以采用如下代码验证:

#include <iostream>
#include <limits>
#include <string>
using namespace std;

int main()
{
    size_t npos = -1;
    cout << "npos: " << npos << endl;
    cout << "size_t max: " << numeric_limits<size_t>::max() << endl;
}

在我的PC上执行结果为:

                 npos:           4294967295

                 size_t max:  4294967295

可见他们是相等的,也就是说npos表示size_t的最大值

二、使用

2.1 如果作为一个 返回值 (return value) 表示没有找到匹配项 ,例如:

#include <iostream>
#include <limits>
#include <string>
using namespace std;

int main()
{
  string filename = "test";
  cout << "filename : " << filename << endl;

  size_t idx = filename.find('.');   //作为return value,表示没有匹配项
  if(idx == string::npos)	
  {
    cout << "filename does not contain any period!" << endl;
  }
}
2.2 但是string::npos作为string的成员函数的一个 长度参数 时,表示“ 直到字符串结束 (until the end of the string)”。例如:
tmpname.replace(idx+1, string::npos, suffix);

这里的string::npos就是一个长度参数,表示直到字符串的结束,配合idx+1表示,string的剩余部分。

#include <iostream>
#include <limits>
#include <string>
using namespace std;

int main()
{
  string filename = "test.cpp";
  cout << "filename : " << filename << endl;

  size_t idx = filename.find('.');   //as a return value
  if(idx == string::npos)	
  {
    cout << "filename does not contain any period!" << endl;
  }
  else
  {
    string tmpname = filename;
    tmpname.replace(idx + 1, string::npos, "xxx"); //string::npos作为长度参数,表示直到字符串结束
    cout << "repalce: " << tmpname << endl;
  }
}

执行结果为:

filename:test.cpp

replace: test.xxx      


#include <iostream> #include <string> #include <windows.h> #include <vector> #include <iomanip> #include <sstream> using namespace std; // 转换FILETIME到本地时间字符串 string FileTimeToString(const FILETIME& ft) { SYSTEMTIME st; FileTimeToSystemTime(&ft, &st); char buffer[26]; sprintf_s(buffer, "%04d-%02d-%02d %02d:%02d:%02d", st.wYear, st.wMonth, st.wDay, st.wHour, st.wMinute, st.wSecond); return string(buffer); } // 获取文件创建时间 FILETIME GetFileCreationTime(const string& filePath) { HANDLE hFile = CreateFileA(filePath.c_str(), GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); FILETIME ftCreation = {0}; if (hFile != INVALID_HANDLE_VALUE) { FILETIME ftAccess, ftWrite; if (GetFileTime(hFile, &ftCreation, &ftAccess, &ftWrite)) { // 时间获取成功 } CloseHandle(hFile); } return ftCreation; } // 比较两个FILETIME(time1 >= time2 返回true) bool CompareFileTime(const FILETIME& time1, const FILETIME& time2) { return (::CompareFileTime(&time1, &time2) >= 0); } // 搜索符合条件的文件 vector<string> SearchFiles(const string& directory, const string& fileType, const FILETIME& startTime, const FILETIME& endTime) { vector<string> result; string searchPath = directory + "\\*"; WIN32_FIND_DATAA findData; HANDLE hFind = FindFirstFileA(searchPath.c_str(), &findData); if (hFind != INVALID_HANDLE_VALUE) { do { // 跳过当前目录和上级目录 if (strcmp(findData.cFileName, ".") == 0 || strcmp(findData.cFileName, "..") == 0) { continue; } // 构建完整路径 string fullPath = directory + "\\" + findData.cFileName; // 处理目录递归搜索 if (findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { vector<string> subFiles = SearchFiles(fullPath, fileType, startTime, endTime); result.insert(result.end(), subFiles.begin(), subFiles.end()); continue; } // 检查文件类型 string fileName = findData.cFileName; size_t dotPos = fileName.find_last_of('.'); string ext = (dotPos != string::npos) ? fileName.substr(dotPos + 1) : ""; if (!fileType.empty() && _stricmp(ext.c_str(), fileType.c_str()) != 0) { continue; } // 检查创建时间 FILETIME creationTime = findData.ftCreationTime; if ((CompareFileTime(creationTime, startTime) || (startTime.dwHighDateTime == 0 && startTime.dwLowDateTime == 0)) && (CompareFileTime(endTime, creationTime) || (endTime.dwHighDateTime == 0 && endTime.dwLowDateTime == 0))) { result.push_back(fullPath); } } while (FindNextFileA(hFind, &findData) != 0); FindClose(hFind); } return result; } // 重命名文件 bool RenameFile(const string& oldPath, const string& newPath) { if (MoveFileA(oldPath.c_str(), newPath.c_str())) { cout << "成功: " << oldPath << " -> " << newPath << endl; return true; } else { DWORD error = GetLastError(); cout << "错误: 重命名失败 - " << oldPath << " 错误码: " << error << endl; return false; } } // 转换用户输入的日期为FILETIME FILETIME StringToFileTime(const string& dateStr) { SYSTEMTIME st = {0}; if (dateStr.length() >= 10) { sscanf_s(dateStr.c_str(), "%4d-%2d-%2d", &st.wYear, &st.wMonth, &st.wDay); FILETIME ft; SystemTimeToFileTime(&st, &ft); return ft; } // 返回0表示不限制时间 FILETIME zero = {0}; return zero; } int main() { cout << "===== 文件搜索与重命名工具 (VS2008兼容版) =====" << endl; // 设置搜索目录 string directory; cout << "请输入搜索目录 (例如: C:\\MyFiles): "; getline(cin, directory); // 获取文件类型筛选条件 string fileType; cout << "请输入文件类型 (如txt, jpg, 留空则不限制): "; getline(cin, fileType); // 获取时间范围 string startDate, endDate; cout << "请输入开始日期 (格式: YYYY-MM-DD, 留空则不限制): "; getline(cin, startDate); cout << "请输入结束日期 (格式: YYYY-MM-DD, 留空则不限制): "; getline(cin, endDate); FILETIME startTime = StringToFileTime(startDate); FILETIME endTime = StringToFileTime(endDate); // 搜索文件 cout << "\n正在搜索文件..." << endl; vector<string> files = SearchFiles(directory, fileType, startTime, endTime); if (files.empty()) { cout << "未找到符合条件的文件!" << endl; system("pause"); return 0; } // 显示搜索结果 cout << "\n找到 " << files.size() << " 个文件:" << endl; for (size_t i = 0; i < files.size(); i++) { size_t pos = files[i].find_last_of("\\/"); string fileName = (pos != string::npos) ? files[i].substr(pos + 1) : files[i]; cout << "[" << setw(3) << i+1 << "] " << fileName << endl; } // 选择重命名模式 int renameMode; cout << "\n请选择重命名模式:" << endl; cout << "1. 添加前缀" << endl; cout << "2. 添加后缀" << endl; cout << "3. 替换文本" << endl; cout << "4. 序列编号" << endl; cout << "请输入选项 (1-4): "; cin >> renameMode; cin.ignore(); string prefix, suffix, oldText, newText; int startNum = 1; string format; switch (renameMode) { case 1: cout << "请输入要添加的前缀: "; getline(cin, prefix); break; case 2: cout << "请输入要添加的后缀: "; getline(cin, suffix); break; case 3: cout << "请输入要替换的文本: "; getline(cin, oldText); cout << "请输入替换后的文本: "; getline(cin, newText); break; case 4: cout << "请输入起始编号: "; cin >> startNum; cin.ignore(); cout << "请输入格式字符串 (例如: file_%%03d): "; getline(cin, format); break; default: cout << "无效的选项!" << endl; system("pause"); return 1; } // 执行重命名 int successCount = 0; cout << "\n==== 开始重命名 ====" << endl; for (size_t i = 0; i < files.size(); i++) { string filePath = files[i]; size_t lastSlash = filePath.find_last_of("\\/"); size_t lastDot = filePath.find_last_of("."); string path = (lastSlash != string::npos) ? filePath.substr(0, lastSlash + 1) : ""; string fileName = (lastSlash != string::npos) ? filePath.substr(lastSlash + 1) : filePath; string name = (lastDot != string::npos && lastDot > lastSlash) ? fileName.substr(0, lastDot - lastSlash - 1) : fileName; string ext = (lastDot != string::npos && lastDot > lastSlash) ? fileName.substr(lastDot) : ""; string newName; if (renameMode == 1) { newName = prefix + name + ext; } else if (renameMode == 2) { newName = name + suffix + ext; } else if (renameMode == 3) { // 替换文本 size_t pos = 0; while ((pos = name.find(oldText, pos)) != string::npos) { name.replace(pos, oldText.length(), newText); pos += newText.length(); } newName = name + ext; } else if (renameMode == 4) { // 序列编号 char numBuffer[20]; sprintf_s(numBuffer, format.c_str(), startNum++); newName = numBuffer + ext; } string newFilePath = path + newName; if (RenameFile(filePath, newFilePath)) { successCount++; } } cout << "\n==== 重命名完成 ====" << endl; cout << "成功重命名 " << successCount << " 个文件" << endl; cout << "失败 " << files.size() - successCount << " 个" << endl; system("pause"); return 0; }运行后出现错误:TEST_file_Rename.exe 中的 0x7c812aeb 处未处理的异常: Microsoft C++ 异常: 内存位置 0x0012f740 处的 std::out_of_range。基于vs2008向我提供优化后的代码
最新发布
06-24
#include <iostream> #include <string> using namespace std; // 验证用户ID格式 bool validateUserID(string userID) { if (userID.length() != 6) { return false; } if (userID[0] != 'U') { return false; } for (int i = 1; i < 5; i++) { if (userID[i] < '0' || userID[i] > '9') { return false; } } if (userID[5] != 'A' && userID[5] != 'B' && userID[5] != 'C') { return false; } return true; } // 分类评论内容 string classifyCommentLength(string comment) { int len = comment.length(); if (len < 10) { return "SHORT"; } else if (len <= 50) { return "MEDIUM"; } else { return "LONG"; } } // 标记评论质量 string markCommentQuality(string comment) { if (comment.find("refund") != string::npos || comment.find("bad") != string::npos) { return "NEGATIVE"; } else if (comment.find("great") != string::npos || comment.find("good") != string::npos) { return "POSITIVE"; } else { return "NEUTRAL"; } } // 检查评论有效性 string checkCommentValidity(int score, string purchaseTime, string commentTime) { // 这里简单比较字符串大小来判断时间先后,实际可使用更严谨的日期时间处理 if (purchaseTime > commentTime) { return "INVALID_TIME"; } if (score < 1 || score > 5) { return "INVALID_SCORE"; } return ""; } // 评估评论可信度 string evaluateCommentCredibility(string comment, string purchaseTime, string commentTime) { // 简单假设两个日期格式为YYYY-MM-DD,手动提取年、月、日来计算天数差 int commentYear, commentMonth, commentDay; int purchaseYear, purchaseMonth, purchaseDay; sscanf(commentTime.c_str(), "%d-%d-%d", &commentYear, &commentMonth, &commentDay); sscanf(purchaseTime.c_str(), "%d-%d-%d", &purchaseYear, &purchaseMonth, &purchaseDay); // 简单计算天数差,未考虑月份天数差异等复杂情况 int daysDiff = (commentYear - purchaseYear) * 365 + (commentMonth - purchaseMonth) * 30 + (commentDay - purchaseDay); int len = comment.length(); if (len > 20 && daysDiff <= 7) { return "HIGH"; } else if (daysDiff > 30) { return "LOW"; } else { return "MEDIUM"; } } int main() { int n; cout << "请输入评论数量: "; cin >> n; cin.ignore(); // 清除缓冲区的换行符 for (int i = 0; i < n; i++) { string userID, comment, purchaseTime, commentTime; int score; cout << "请输入用户ID: "; getline(cin, userID); cout << "请输入评论内容: "; getline(cin, comment); cout << "请输入评分: "; cin >> score; cin.ignore(); cout << "请输入购买时间(YYYY-MM-DD): "; getline(cin, purchaseTime); cout << "请输入评论时间(YYYY-MM-DD): "; getline(cin, commentTime); if (!validateUserID(userID)) { cout << "INVALID_USER_ID_FORMAT" << endl; continue; } string validity = checkCommentValidity(score, purchaseTime, commentTime); if (!validity.empty()) { cout << validity << endl; continue; } string lengthType = classifyCommentLength(comment); string quality = markCommentQuality(comment); string credibility = evaluateCommentCredibility(comment, purchaseTime, commentTime); cout << lengthType << " " << quality << " " << credibility << endl; } return 0; }
03-23
#include <iostream> #include <string> #include <windows.h> #include <vector> #include <iomanip> #include <sstream> #include <ctime> #include <io.h> using namespace std; // 转换FILETIME到本地时间字符串 string FileTimeToString(const FILETIME& ft) { SYSTEMTIME st; FileTimeToSystemTime(&ft, &st); char buffer[26]; sprintf_s(buffer, "%04d-%02d-%02d %02d:%02d:%02d", st.wYear, st.wMonth, st.wDay, st.wHour, st.wMinute, st.wSecond); return string(buffer); } // 获取文件创建时间 FILETIME GetFileCreationTime(const string& filePath) { HANDLE hFile = CreateFileA(filePath.c_str(), GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); FILETIME ftCreation = {0}; if (hFile != INVALID_HANDLE_VALUE) { FILETIME ftAccess, ftWrite; if (GetFileTime(hFile, &ftCreation, &ftAccess, &ftWrite)) { // 转换为本地时间(可选) // SYSTEMTIME stLocal; // FileTimeToSystemTime(&ftCreation, &stLocal); } CloseHandle(hFile); } return ftCreation; } // 比较两个FILETIME(time1 >= time2 返回true) bool CompareFileTime(const FILETIME& time1, const FILETIME& time2) { if (time1.dwHighDateTime > time2.dwHighDateTime) return true; if (time1.dwHighDateTime < time2.dwHighDateTime) return false; return time1.dwLowDateTime >= time2.dwLowDateTime; } // 搜索符合条件的文件 vector<string> SearchFiles(const string& directory, const string& fileType, const FILETIME& startTime, const FILETIME& endTime) { vector<string> result; string searchPath = directory + "\\*.*"; WIN32_FIND_DATAA findData; HANDLE hFind = FindFirstFileA(searchPath.c_str(), &findData); if (hFind != INVALID_HANDLE_VALUE) { do { // 跳过当前目录和上级目录 if (strcmp(findData.cFileName, ".") == 0 || strcmp(findData.cFileName, "..") == 0) { continue; } // 跳过目录 if (findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { continue; } // 检查文件类型 string fileName = findData.cFileName; size_t dotPos = fileName.find_last_of('.'); string ext = (dotPos != string::npos) ? fileName.substr(dotPos + 1) : ""; if (!fileType.empty() && _stricmp(ext.c_str(), fileType.c_str()) != 0) { continue; } // 检查创建时间 FILETIME creationTime = GetFileCreationTime(directory + "\\" + fileName); if ((CompareFileTime(creationTime, startTime) || startTime.dwHighDateTime == 0) && (CompareFileTime(endTime, creationTime) || endTime.dwHighDateTime == 0)) { result.push_back(directory + "\\" + fileName); } } while (FindNextFileA(hFind, &findData) != 0); FindClose(hFind); } return result; } // 重命名文件 bool RenameFile(const string& oldPath, const string& newPath) { cout << "尝试重命名: " << oldPath << " -> " << newPath << endl; if (_access(oldPath.c_str(), 0) != 0) { cout << "错误: 源文件不存在 - " << oldPath << endl; return false; } if (_access(newPath.c_str(), 0) == 0) { cout << "错误: 目标文件已存在 - " << newPath << endl; return false; } if (MoveFileA(oldPath.c_str(), newPath.c_str())) { cout << "成功: " << newPath << endl; return true; } else { DWORD error = GetLastError(); cout << "错误: 重命名失败 - 错误码: " << error << endl; return false; } } // 转换用户输入的日期为FILETIME FILETIME StringToFileTime(const string& dateStr) { // 格式示例: "2023-01-01 12:00:00" SYSTEMTIME st = {0}; if (dateStr.length() >= 19) { sscanf_s(dateStr.c_str(), "%4d-%2d-%2d %2d:%2d:%2d", &st.wYear, &st.wMonth, &st.wDay, &st.wHour, &st.wMinute, &st.wSecond); FILETIME ft; SystemTimeToFileTime(&st, &ft); return ft; } // 返回0表示不限制时间 return {0}; } int main() { cout << "===== 文件搜索与重命名工具 =====" << endl; // 设置搜索目录(默认为E盘) string directory = "E:\\"; cout << "搜索目录: " << directory << endl; // 获取文件类型筛选条件 string fileType; cout << "请输入文件类型(如txt、jpg,留空则不限制): "; getline(cin, fileType); // 获取时间范围 string startDate, endDate; cout << "请输入开始日期 (格式: YYYY-MM-DD HH:MM:SS,留空则不限制): "; getline(cin, startDate); cout << "请输入结束日期 (格式: YYYY-MM-DD HH:MM:SS,留空则不限制): "; getline(cin, endDate); FILETIME startTime = StringToFileTime(startDate); FILETIME endTime = StringToFileTime(endDate); // 搜索文件 cout << "\n正在搜索文件..." << endl; vector<string> files = SearchFiles(directory, fileType, startTime, endTime); if (files.empty()) { cout << "未找到符合条件的文件!" << endl; system("pause"); return 0; } // 显示搜索结果 cout << "\n找到 " << files.size() << " 个文件:" << endl; for (size_t i = 0; i < files.size(); i++) { FILETIME ft = GetFileCreationTime(files[i]); cout << "[" << setw(2) << i+1 << "] " << files[i] << " (创建于: " << FileTimeToString(ft) << ")" << endl; } // 选择重命名模式 int renameMode; cout << "\n请选择重命名模式:" << endl; cout << "1. 添加前缀" << endl; cout << "2. 添加后缀" << endl; cout << "3. 替换文本" << endl; cout << "4. 序列编号" << endl; cout << "请输入选项 (1-4): "; cin >> renameMode; cin.ignore(); // 清除输入缓冲区 string prefix, suffix, oldText, newText; int startNum = 1; string format; switch (renameMode) { case 1: cout << "请输入要添加的前缀: "; getline(cin, prefix); break; case 2: cout << "请输入要添加的后缀: "; getline(cin, suffix); break; case 3: // 关键修改:将代码块改为单行语句,避免VS2008的语法解析错误 cout << "请输入要替换的文本: "; getline(cin, oldText); cout << "请输入替换后的文本: "; getline(cin, newText); break; case 4: cout << "请输入起始编号: "; cin >> startNum; cin.ignore(); cout << "请输入格式字符串 (例如: img_%%03d): "; getline(cin, format); break; default: cout << "无效的选项!" << endl; system("pause"); return 1; } // 执行重命名 int successCount = 0; int failCount = 0; cout << "\n==== 开始重命名 ====" << endl; for (size_t i = 0; i < files.size(); i++) { const string& filePath = files[i]; size_t lastSlash = filePath.find_last_of("\\/"); size_t lastDot = filePath.find_last_of("."); string path = (lastSlash != string::npos) ? filePath.substr(0, lastSlash + 1) : ""; string fileName = (lastSlash != string::npos) ? filePath.substr(lastSlash + 1) : filePath; string name = (lastDot != string::npos && lastDot > lastSlash) ? fileName.substr(0, lastDot - lastSlash - 1) : fileName; string ext = (lastDot != string::npos && lastDot > lastSlash) ? fileName.substr(lastDot) : ""; string newName = ""; // 使用if-else结构替代复杂的switch-case,提高兼容性 if (renameMode == 1) { newName = prefix + name + ext; } else if (renameMode == 2) { newName = name + suffix + ext; } else if (renameMode == 3) { // 关键修改:将代码块改为单行语句,避免VS2008的语法解析错误 string newFileName = name; size_t pos = 0; while ((pos = newFileName.find(oldText, pos)) != string::npos) { newFileName.replace(pos, oldText.length(), newText); pos += newText.length(); } newName = newFileName + ext; } else if (renameMode == 4) { char buffer[1024]; string fmt = format; size_t pos = 0; while ((pos = fmt.find("%%", pos)) != string::npos) { fmt.replace(pos, 2, "%"); pos += 1; } sprintf_s(buffer, fmt.c_str(), startNum++); newName = buffer + ext; } string newFilePath = path + newName; if (RenameFile(filePath, newFilePath)) { successCount++; } else { failCount++; } } cout << "\n==== 重命名完成 ====" << endl; cout << "成功: " << successCount << " 个" << endl; cout << "失败: " << failCount << " 个" << endl; system("pause"); return 0; }
06-24
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值