#include <iostream>
#include <string>
#include <fstream>
#include <limits>
void cat(std::string filename);
void echo(std::string args);
void cp(std::string source, std::string destination);
int main()
{
std::string command = "", prompt = "$ ";
std::cout << std::endl << prompt;
while (std::cin >> command)
{
if (command == "cat")
{
std::string source = "", arg = "";
std::cin >> source;
if (std::getline(std::cin, arg) && arg.size() > 0)
{
std::cerr << "cat only accepts one argument" << std::endl << prompt;
continue;
}
else
std::cin.clear();
cat(source);
}
else if (command == "echo")
{
std::string args;
while (std::cin.peek() == ' ')
std::cin.get();
std::getline(std::cin, args);
echo(args);
}
else if (command == "cp")
{
std::string source = "", destination = "", arg = "";
std::cin >> source >> destination;
if (std::getline(std::cin, arg) && arg.size() > 0)
{
std::cerr << "cp only accepts two arguments" << std::endl << prompt;
continue;
}
else
std::cin.clear();
cp(source, destination);
}
else if (command == "PS1")
{
while (std::cin.peek() == ' ')
std::cin.get();
std::getline(std::cin, prompt);
}
else if (command == "exit")
{
break;
}
else if (command == "ls")
{
system("ls");
}
else
{
std::cout << "Usage: " << std::endl
<< "cat [filename]" << std::endl
<< "\tDisplays file contents." << std::endl << std::endl
<< "echo [-n] [args ...]" << std::endl
<< "\tWrite arguments to the standard output." << std::endl << std::endl
<< "PS1 [prompt]" << std::endl
<< "\tChanges the prompt symbol(s)." << std::endl << std::endl
<< "cp [source] [destination]" << std::endl
<< "\tCopies the source file to the destination file." << std::endl << std::endl
<< "exit" << std::endl
<< "\tExits this prompt." << std::endl << std::endl;
}
std::cout << prompt;
}
return 0;
}
void cat(std::string filename)
{
std::ifstream file;
file.open(filename);
std::string line = "";
if (!file)
{
std::cerr << "File open error" << std::endl;
return;
}
while (std::getline(file, line))
std::cout << line << std::endl;
}
void echo(std::string args)
{
if (args.size() > 2 && args.substr(0, 3) == "-n ")
{
args = args.substr(3);
std::cout << args;
}
else if (args == "-n")
return;
else
std::cout << args << std::endl;
}
void cp(std::string source, std::string destination)
{
std::ifstream sourceFile;
std::ofstream destinationFile;
sourceFile.open(source);
destinationFile.open(destination);
std::string line = "";
while (std::getline(sourceFile, line))
destinationFile << line << std::endl;
}