Argc Argv
#include <iostream>
#include <vector>
#include <fstream>
using namespace std;
bool vec2file(const vector<string> &s, string filename)
{
//write vector to a file
ofstream fout(filename);
for (unsigned int x=0; x<s.size(); x++)
{
fout << s[x] << endl;
}
fout.close();
return true;
}
vector<string> file2vec(string filename)
{
//read a file and return vector
vector <string> strvect;
string line;
ifstream fin(filename);
while (getline(fin,line))
{
strvect.push_back(line);
}
fin.close();
return strvect;
}
int main(int argc, char* argv[])
{
string fname = argv[1];
vector <string> food = file2vec(fname);
string grocery("");
while (1)
{
cout<<"enter grocery to buy or quit to end: ";
getline(cin, grocery);
if (grocery == "quit")
break;
food.push_back(grocery);
}
cout<<"\nprinting list of groceries to buy"<<endl;
for (unsigned int y=0; y<food.size(); y++)
{
cout << food[y] << endl;
}
vec2file(food, fname);
return 0;
}
Try/Catch
#include <iostream>
#include <vector>
#include <fstream>
using namespace std;
bool vec2file(const vector<string> &s, string filename)
{
try
{
ofstream fout(filename);
if (!fout.good()) //need to check if file is truly open (in case directory is read only)
throw(1);
for (unsigned int x=0; x<s.size(); x++)
{
fout << s[x] << endl;
}
fout.close();
}
catch (int e)
{
cout << "Error code: "<< e <<endl;
return false;
}
return true;
}
bool file2vec( string filename, vector<string> &strvect)
{
strvect.clear(); //to be sure vector is empty to begin
string line;
try
{
ifstream fin(filename);
if (!fin.good())
throw(1);
while (getline(fin,line))
{
strvect.push_back(line);
}
fin.close();
}
catch (int e)
{
cout << "Error code: "<< e <<endl;
return false;
}
return true;
}
int main(int c, char* argv[])
{
vector<string> vect(3, "hello test");
string filen(argv[1]);
if (vec2file(vect,filen)) cout << "File successfuly saved";
else cout << "File not saved";
cin.get(); //pause
vector<string> newvect;
if (file2vec(filen, newvect))
{
cout << "success" <<endl;
for (unsigned int y=0; y<newvect.size(); y++)
{
cout << newvect[y] << endl;
}
}
else
{
cout<< "failure to read file: "<<filen<<endl;
return 1;
}
return 0;
}