简体   繁体   English

在 c++ 中的目录中创建子文件夹会引发语法错误

[英]Creating a subfolder in a directory in c++ throws syntax error

I'm trying to create a subdirectory with today's date in a folder.我正在尝试在文件夹中创建一个包含今天日期的子目录。 The code compiles succesfully, but throws an error during runtime.代码编译成功,但在运行时抛出错误。

#include <iostream>
#include <chrono>
#include <sstream>
#include <iomanip>
#include <bits/stdc++.h> 
#include <sys/stat.h> 
#include <sys/types.h> 

using namespace std;

int main()
{    
    // First create the directory with username
    if (mkdir("Anita_", 0777) == -1) 
        cerr << "Error :  " << strerror(errno) << endl; 
    else
        cout << "Directory created"; 
    
    //Pull out 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");
    
    //Prepare for subdirectory creating
    std::cout << ss.str() << std::endl;
    string str_="mkdir -p Anita_/ss.str()";
    const char *com=str_.c_str();
    system(com);
    //system("mkdir -p Anita_/ss.str().c_str()");

}

During runtime I'm getting this error:在运行时我收到此错误:

sh: 1: Syntax error: "(" unexpected sh:1:语法错误:“(”意外

Is it possible to use mkdir() instead of system() , like mkdir('Anita_/ss.str().c_str()', 0700);是否可以使用mkdir()而不是system() ,例如mkdir('Anita_/ss.str().c_str()', 0700);

You can't put ss.str() inside double quotes and expect the shell to execute the C++ code.您不能将ss.str()放在双引号内并期望 shell 执行 C++ 代码。

Instead you should evaluate ss.str() in your program and pass the results to the shell相反,您应该在程序中评估ss.str()并将结果传递给 shell

string str_ = "mkdir -p Anita_/" + ss.str();
const char *com = str_.c_str();
system(com);

This version uses + to append "mkdir -p Anita_/" and the result of ss.str() in your program before passing that command to the shell.此版本使用+到 append "mkdir -p Anita_/" ,并在将该命令传递给 shell之前在程序中使用ss.str()的结果。

BTW there are two variables there you don't need, this one line of code does the same thing顺便说一句,那里有两个你不需要的变量,这一行代码做同样的事情

system(("mkdir -p Anita_/" + ss.str()).c_str());

or if that seems a bit complicated you could do this或者如果这看起来有点复杂你可以这样做

string str_ = "mkdir -p Anita_/" + ss.str();
system(str_.c_str());

which at least gets rid of one variable.这至少摆脱了一个变量。

You don't have to use a variable everytime you call a function, you can call a function with an expression .您不必每次调用 function 时都使用变量,您可以使用表达式调用 function。

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

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