0

My system is Ubuntu 20.04. Suppose I am in project directory and this directory contains these folders/files: test, hello.txt. I wrote the following program:-

#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;
}

And then I will test as first argument of the program while running it. I expected it will print all files and folders in test folder. But it gave me an error. Can someone tell me, what is the error and how to fix it?

2 Answers2

3

What you do in your code is not correct, You add two pointers, and the result you will clearly not be what you expect. Use std::string. So your code will look like this:

#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;
}

Usually using the system function is a bad practice, so in your case I would rather use the functionality that performs your task: display all files in folder. Together with your code, it will look like this:

#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;
}
Deumaudit
  • 978
  • 7
  • 17
  • What does this data do in system? When I directly put command, it says system function can't work with string? How can this data method make it works correctly? Even I also tried to convert string to char*, but it said we can't convert string to char*. –  Sep 22 '21 at 16:04
  • 1
    There is documentation of string::data() here: [https://en.cppreference.com/w/cpp/string/basic_string/data](https://en.cppreference.com/w/cpp/string/basic_string/data) – drescherjm Sep 22 '21 at 16:09
0
  1. Don't use using namespace std. It pollutes the global namespace. Use std:: prefix.
  2. You can't use + operator on C-strings. Use std::string instead (you are using C++, aren't you?).
  3. Check for the number of arguments provided: if it's 0 then your program will crash.
  4. Better return the value returned by 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());
}
Zakk
  • 1,935
  • 1
  • 6
  • 17