Using iterators, ifstream, ofstream, how it was done

I have a txt file containing a bunch of words, one per line. I need to read this file and put each word in the list so the user will be able to change this list when editing, the program will write the changed list to a new file.

Since the object is an object orinted C ++, I will have two classes: one for reading / writing to a file and one for editing / mess with the list and user.

given this approach, here is my first class read function:

bool FileMgr::readToList(list<string> &l)
{
if(!input.is_open())
    return false;

string line;
while(!input.eof())
{
    getline(input, line);
    l.push_back(line);
}
return true;
}

Keep in mind: input opens in the constructor. questions: is there a less redundant way to get this damn line from istream and push it to l? (without a "line" between them). questions aside, these functions seem to work correctly.

now output function:

 bool FileMgr::writeFromList(list<string>::iterator begin, list<string>::iterator end)
{
    ofstream output;
    output.open("output.txt");
    while(begin != end)
    {
        output << *begin << "\n";
        begin++;
    }
    output.close();
    return true;
}

:

    FileMgr file;
list<string> words;
file.readToList(words);
cout << words.front() << words.back();
list<string>::iterator begin = words.begin();
list<string>::iterator end = words.end();
file.writeFromList(begin, end);

, . , ? getline (, ), , - ?

+3
2

, . eof , eof, . , bad fail. , , , . ++ basic_ios.

readToList :

std::string line;
while (std::getline(input, line))
{
    l.push_back(line);
}

++- , . cin - ++? , STL ++.

writeFromList, , . ++ : . , ; .

output.close(): std::ofstream.

std::copy std::ostream_iterator, :

template <typename ForwardIterator>
bool FileMgr::writeFromList(ForwardIterator first, ForwardIterator last)
{
    std::ofstream output("output.txt");

    std::copy(first, last, std::ostream_iterator<std::string>(output, ""));
}
+6

writeFromList . - , , stdlib.

:

bool FileMgr::writeFromList(list<string>::iterator it, list<string>::iterator end)
{
    ofstream output("output.txt");

    for (; it != end; ++it)
        output << *it;

    return true;
}

file.writeFromList(words.begin(), words.end());

, .

writeFromList . .

, .eof . :

string line;
while (getline(input, line))
    l.push_back(line);
+2

All Articles