【发布时间】:2013-07-29 06:58:38
【问题描述】:
我想在另一个目录中创建 2 个目录。目录将具有随机生成的名称。但我遇到了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;
}
【问题讨论】:
-
你能把
std::cout << "dirname : " << dirname_ << std::endl;移动到第二个循环中,看看dirname_在调用stat时实际上是什么吗? -
您是否考虑过使用
g++ -Wall -g进行编译并使用gdb调试器(也许还使用strace您的程序)? -
为什么你期望 stat 的输出非零?