【问题标题】:Error checking for empty directory in C++在 C++ 中检查空目录时出错
【发布时间】:2021-01-17 08:57:25
【问题描述】:

我正在尝试创建一个以今天日期命名的文件夹(在 Ubuntu 上),然后检查它是否为空。

每天都会进行几次空或不检查。

#include <cstdlib>
#include <unistd.h>
#include <stdio.h>
#include <iostream>
#include <typeinfo>
#include <chrono>
#include <time.h>
#include <iomanip>

using namespace std; 

int main() {
  //Pull out system date and create a folder named by system date
  auto const now = std::chrono::system_clock::now();
  auto const in_time_t = std::chrono::system_clock::to_time_t(now);
  std::stringstream ss;
  ss << std::put_time(std::localtime(&in_time_t), "%d_%m_%Y"); 
    
  // Creating todays date folder with entry folder
  string str_2=std::string("mkdir -p " + string(ss.str()) + "/entry");
  const char *com2=str_2.c_str();
  system(com2);
   
  //check if directory is empty or not
  int check;
  char is_empty[100];
  FILE * output;
  output = popen("ls " + ss.str() + "/entry | wc -l","r") ; 
  fgets (is_empty, 100, output); //write to the char
  pclose (output);
  check = atoi(is_empty);
  if (check == 0) {
    cout << "The folder is empty" << endl;
  } 
}

编译此代码时出现此错误:

error: no match for ‘operator+’ (operand types are ‘const char [4]’ 
    and ‘std::stringstream {aka std::__cxx11::basic_stringstream<char>}’)
         output = popen("ls " +ss+ "/entry | wc -l","r") ;

【问题讨论】:

  • 改为std::string cmd = "ls " +ss+ "/entry | wc -l"; output = popen(cmd.c_str(),"r");
  • 错误:'operator+' 不匹配(操作数类型为 'const char [4]' 和 'std::stringstream {aka std::__cxx11::basic_stringstream}')std: :string cmd="ls" +ss+ "/entry | wc -l"; del.cpp:58:27: 注意: 候选: operator+(const char*, long int) del.cpp:58:27: 注意: 'std::stringstream {aka 中的参数 2 没有已知的转换std::__cxx11::basic_stringstream}' 到 'long int'
  • 谁能帮忙!!!
  • 您也可以append a s to your string literals,以便在构建字符串时更轻松地使用它们:std::string cmd = "ls "s +ss+ "/entry | wc -l"s;。这使它更容易。您不能使用 + 连接原始 c 样式。这基本上就是您面临的问题。
  • 试过了,但仍然是错误:- 错误:'operator+' 不匹配(操作数类型是 'std::__cxx11::basic_string' 和 'std::stringstream {aka std: :__cxx11::basic_stringstream}') std::string cmd = "ls "s +ss+ "/entry | wc -l"s;

标签: c++


【解决方案1】:

这帮我解决了

int check;
char is_empty[100];
FILE * output;

string cmd = std::string("ls " + string(ss.str())+ "/entry | wc -l") ;
const char *com4 = cmd.c_str(); 
output = popen(com4,"r");
fgets(is_empty, 100, output);
pclose (output);
check = atoi(is_empty);
//cout << check<<endl;
if (check == 0){
    cout << "The folder is empty" << endl;
   }

【讨论】:

  • 不要解析来自ls 的输出。编译时添加-std=c++17(或更高版本的标准)并改用std::filesystem::directory_iterator
  • @TedLyngmo 文件系统无法在我的 ubuntu 上运行。尝试了一切,但它根本没有被检测到,即使它在 /usr/lib 中并且我链接并包含在路径等中。
  • 还是同样的错误:未定义的对 `boost::system::generic_category()' 的引用
  • #include #include int main() { if ( !boost::filesystem::exists( "myfile.txt" ) ) { std::cout
猜你喜欢
  • 1970-01-01
  • 2012-07-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-08-09
  • 2011-09-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多