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?
CodePudding user response:
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;
}
CodePudding user response:
- Don't use
using namespace std
. It pollutes the global namespace. Usestd::
prefix. - You can't use
std::string
instead (you are using C , aren't you?). - Check for the number of arguments provided: if it's
0
then your program will crash. - 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());
}