简体   繁体   English

具有变量的C ++文件/目录状态

[英]C++ File/Directory stat with variable

I'm trying to check if directory exist. 我正在尝试检查目录是否存在。 I want to make it more reliable and I'm trying to use stat with predefined variable which check user name, but all the time I'm getting an error. 我想使其更可靠,并且尝试使用带有预定义变量的stat来检查用户名,但是始终会出现错误。

Here's userdir string output : /home/root/test 这是userdir字符串输出:/ home / root / test

    string userdir="/home/"+user+"/test";

  struct stat st ;
  if(stat(userdir, &st) == 0)
    printf( "test directory exist\n" );
  else
    printf("test directory don't exist\n");

stat() takes a const char * , not an std::string : stat()采用const char * ,而不是std::string

if (stat(userdir.c_str(), &st) == 0)
//               ^^^^^^^

If string is std::string then you need to call stat(userdir.c_str(), &st) - stat takes a C style string, not a C++ one. 如果stringstd::string ,那么你需要调用stat(userdir.c_str(), &st) - stat需要一个C风格的字符串,而不是C ++的一个。

Minimal example: 最小示例:

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

int main() {
  const std::string dir="/tmp";
  struct stat st;

  return stat(dir, &st); // Error

  return stat(dir.c_str(), &st); // Correct
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM