“stat()”的一些奇怪行为

some strange behaviour of `stat()`

本文关键字:stat      更新时间:2023-10-16

我想创建两个目录,一个在另一个目录中。目录将具有随机生成的名称。但我发现stat()函数有一些奇怪的行为。

对于dirname_stat()的每次调用都返回0。但是workdir_中没有文件。仍然找不到我的代码中有什么错误。

Linux computer 3.8.0-26-generic #38-Ubuntu SMP Mon Jun 17 21:43:33 UTC 2013 x86_64 x86_64 x86_64 GNU/Linux 上编译

以下是来源:

#include <string>
#include <stdexcept>
#include <iostream>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <stdlib.h>

const std::string _randomStr(const int len) {
    static const char alphanum[] =
        "0123456789"
        "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
        "abcdefghijklmnopqrstuvwxyz";
    std::string s(len + 1, 0);
    for (int i = 0; i < len; ++i) {
        s[i] = alphanum[rand() % (sizeof(alphanum) - 1)];
    }
    return s;
}
int main(void)
{
    std::string workdir_;
    std::string dirname_;
    struct stat sb;
    int err = 0;
    do {
        workdir_ = "./" + _randomStr(10);
    } while (0 == ::stat(workdir_.c_str(), &sb));
    err = ::mkdir(workdir_.c_str(), 0755);
    if (err)
        throw std::runtime_error("failed to initialize directory");
    std::cout << "workdir: " << workdir_ << std::endl;
    do {
        dirname_ = workdir_ + "/" + _randomStr(10);
    } while (0 == ::stat(dirname_.c_str(), &sb));
    err = ::mkdir(dirname_.c_str(), 0755);
    if (err)
        throw std::runtime_error("failed to initialize directory");
    std::cout << "dirname : " << dirname_ << std::endl;     
    return 0;
}

您的dirname_中有一个伪造的。当您在循环中打印目录名并运行strace时,输出看起来像

write(2, "dirname : ", 10)              = 10
write(2, "./zLOZ2nOXpP/7U20o0J90x", 25) = 25
write(2, "n", 1)                       = 1
stat("./zLOZ2nOXpP", {st_mode=S_IFDIR|0755, st_size=4096, ...}) = 0

因此,cerrcout正确地打印字符串(使用其长度),但当使用c_str()转换为C字符串时,结果只是第一个目录名,然后将其传递给stat()