Reputation:
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?
Upvotes: 0
Views: 1159
Reputation: 2063
using namespace std
. It pollutes the global namespace. Use std::
prefix.+
operator on C-strings. Use std::string
instead (you are using C++, aren't you?).0
then your program will crash.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());
}
Upvotes: 0
Reputation: 1016
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;
}
Upvotes: 3