Skip to content

Commit c6fcd29

Browse files
committed
feat:1.10.1, 为util::fs添加Rename()函数
1 parent 4741207 commit c6fcd29

File tree

4 files changed

+46
-1
lines changed

4 files changed

+46
-1
lines changed

modules/util/fs.cpp

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -211,6 +211,7 @@ bool RemoveFile(const std::string &filename, bool allow_log_print)
211211

212212
if (errno != ENOENT && allow_log_print)
213213
LogWarn("errno:%d (%s)", errno, strerror(errno));
214+
214215
return false;
215216
}
216217

@@ -429,6 +430,18 @@ std::string Dirname(const std::string &full_path)
429430
return full_path.substr(start_pos, end_pos - start_pos);
430431
}
431432

433+
bool Rename(const std::string &old_name, const std::string &new_name)
434+
{
435+
int ret = ::rename(old_name.c_str(), new_name.c_str());
436+
if (ret == 0)
437+
return true;
438+
439+
if (errno != ENOENT)
440+
LogWarn("errno:%d (%s)", errno, strerror(errno));
441+
442+
return false;
443+
}
444+
432445
}
433446
}
434447
}

modules/util/fs.h

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -255,6 +255,17 @@ const char* Basename(const char *full_path);
255255
*/
256256
std::string Dirname(const std::string &full_path);
257257

258+
/**
259+
* 重命名
260+
*
261+
* \param old_name 旧文件名
262+
* \param new_name 新文件名
263+
*
264+
* \return true 成功
265+
* \return false 失败
266+
*/
267+
bool Rename(const std::string &old_name, const std::string &new_name);
268+
258269
}
259270
}
260271
}

modules/util/fs_test.cpp

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -132,6 +132,27 @@ TEST(fs, BinaryFileReadWrite_Ok) {
132132
EXPECT_FALSE(IsFileExist(test_filename));
133133
}
134134

135+
TEST(fs, RenameFile) {
136+
auto old_name = "old_file";
137+
auto new_name = "new_file";
138+
EXPECT_TRUE(WriteStringToTextFile(old_name, ""));
139+
EXPECT_TRUE(Rename(old_name, new_name));
140+
EXPECT_TRUE(IsFileExist(new_name));
141+
EXPECT_FALSE(IsFileExist(old_name));
142+
RemoveFile(new_name);
143+
}
144+
145+
TEST(fs, RenameDirectory) {
146+
auto old_name = "old_dir";
147+
auto new_name = "new_dir";
148+
EXPECT_TRUE(MakeDirectory(old_name));
149+
EXPECT_TRUE(Rename(old_name, new_name));
150+
EXPECT_TRUE(IsDirectoryExist(new_name));
151+
EXPECT_FALSE(IsFileExist(old_name));
152+
RemoveDirectory(old_name);
153+
}
154+
155+
135156
TEST(fs, IsDirectoryExist) {
136157
EXPECT_FALSE(IsDirectoryExist("should/not/exist/directory"));
137158
EXPECT_TRUE(IsDirectoryExist("/etc/"));

version.mk

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,4 +21,4 @@
2121
# TBOX版本号
2222
TBOX_VERSION_MAJOR := 1
2323
TBOX_VERSION_MINOR := 10
24-
TBOX_VERSION_REVISION := 0
24+
TBOX_VERSION_REVISION := 1

0 commit comments

Comments
 (0)