If you want your function or class to use argc and argv, just pass them on as arguments
cpp code:
#include <iostream>
void printArgs(int argc, char* argv[])
{
for (int i = 0; i < argc; ++i)
{
std::cout << argv[i] << '\n';
}
}
class ArgHolder {
public:
ArgHolder(int argc, char* argv[]) :
m_argc(argc),
m_argv(argv) { }
void print() const
{
for (int i = 0; i < m_argc; ++i)
{
std::cout << m_argv[i] << '\n';
}
}
private:
int m_argc;
char** m_argv;
};
int main(int argc, char* argv[])
{
printArgs(argc, argv);
ArgHolder args(argc, argv);
args.print();
}
If you just want to "read a file", as you stated, you can pass the specific argument (filename) into your function, instead of the whole argv array.
cpp code:
#include <fstream>
#include <iostream>
bool printFile(const char* filename)
{
std::ifstream file(filename);
if (!file)
{
std::cerr << "Failed to open file \"" << filename << "\"!" << std::endl;
return false;
}
file.seekg(0, std::ios::end);
std::ifstream::pos_type length = file.tellg();
file.seekg(0, std::ios::beg);
char* buffer = new char[length];
file.read(buffer, length);
std::cout.write(buffer, length);
delete[] buffer;
return true;
}
int main(int argc, char* argv[])
{
if (argc < 2)
{
std::cout << "Usage: " << argv[0] << "<filename>" << std::endl;
return 1;
}
for (int i = 1; i < argc; ++i)
{
if (!printFile(argv[i]))
{
return 1;
}
}
}
_________________
C++ reference and
C++ FAQMy github page (Give me some love, send me pull requests!)Remember to use a version control system (
Git,
Mercurial) for your projects! They make life a whole lot easier!