windows 及 ubuntu下均验证成功
很容易,一个函数就搞定了,
rename(oldName.c_str(), newName.c_str())
此函数带返回值,0为成功,1为失败。
#include <iostream>
#include <string>
#include <cstdlib>
int main(int argc, char *argv[])
{
std::string oldName, newName;
#ifdef _WIN32
oldName = "F:\\data\\test\\old.jpg";
newName = "F:\\data\\test\\new.jpg";
#else
oldName = "/media/myUbuntu/F/data/test/old.jpg";
newName = "/media/myUbuntu/F/data/test/new.jpg";
#endif
if (!rename(oldName.c_str(), newName.c_str()))
{
std::cout << "rename success "<< std::endl;
}
else
{
std::cout << "rename error "<< std::endl;
}
return 0;
}下面给出一个由于生产文件需要一定时间,且对生产后的文件需要改名的代码策略,
//目的:将前面的“生成pdf”文件进行重新命名,直至重命名
//成功(因为生成pdf文件需要时间,这里的做法能够保证生成pdf完成并且重命名成功!)
while (true)
{
//rename函数带返回值,0为成功,1为失败。
if (rename(filepdfname, newpdfname) == 0)
{
remove(filepdfname);
break;
}
else
{
Sleep(50);
}
}