【发布时间】: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
sto 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++