如何制作 C++ 程序并将在该目录中使用命令行输入和 ls?

How to make a c++ program and will use the command line input and ls in that directory?

我的系统是 Ubuntu 20.04。假设我在 project 目录中,并且该目录包含这些 folders/files:testhello.txt。我写了下面的程序:-

#include <iostream>
#include <string>
#include <cstdlib>
using namespace std;
int main(int argc, char* argv[]){
    const char* command = "ls" + argv[1];
    system(command);
    return 0;
}

然后我将 test 作为程序的第一个参数,而 运行 它。我预计它将打印 test 文件夹中的所有文件和文件夹。但它给了我一个错误。 谁能告诉我错误是什么以及如何解决?

  1. 不要使用 using namespace std。它污染了全局命名空间。使用 std:: 前缀。
  2. 您不能在 C 字符串上使用 + 运算符。请改用 std::string(您使用的是 C++,不是吗?)。
  3. 检查提供的参数数量:如果是 0 那么您的程序将崩溃。
  4. 更好 return return 由 system() 编辑的值。
#include <iostream>
#include <string>
#include <cstdlib>

int main(int argc, const char* argv[])
{
    if (argc < 2) {
        std::cerr << "Specify a folder\n";
        return 1;
    }

    std::string command = "ls " + std::string(argv[1]); // Note the space after ls
    return system(command.c_str());
}

你在代码中所做的不正确,你添加了两个指针,结果显然不是你所期望的。使用 std::string。 所以您的代码将如下所示:

#include <iostream>
#include <string>
#include <cstdlib>
#include <string>

using namespace std;
int main(int argc, char* argv[])
{
    if(argc < 2)
    { 
        cerr << "missing cli argument\n";
        return -1;
    }
    auto command = std::string("ls ") + std::string(argv[1]);
    system(command.data());
    return 0;
}

通常使用 system 函数是一种不好的做法,因此在您的情况下,我宁愿使用执行任务的功能:display all files in folder。连同您的代码,它将如下所示:

#include <string>
#include <iostream>
#include <filesystem>
namespace fs = std::filesystem;

int main(int argc, char* argv[])
{
    if(argc < 2)
    { 
        std::cerr << "missing cli argument\n";
        return -1;
    }
    std::string path = argv[1];
    for (const auto & entry : fs::directory_iterator(path))
        std::cout << entry.path() << std::endl;
    return 0;
}