Yarden Rotem
Yarden Rotem

Reputation: 85

How to swap lines in a text file?

I have a text file; let's say the text file has 10 lines. I want to swap between line 3 and line 6.

How can I do it? Also, I can't create any temporary file for the swap.

Upvotes: 2

Views: 1685

Answers (2)

Rakete1111
Rakete1111

Reputation: 49028

For this solution to work correctly, the lines cannot contain a single whitespace, as that would be used as a delimiter.

const std::string file_name = "data.txt";

// read file into array
std::ifstream ifs{ file_name };
if (!ifs.is_open())
    return -1; // or some other error handling
std::vector<std::string> file;
std::copy(std::istream_iterator<std::string>(ifs), std::istream_iterator<std::string>(), std::back_inserter(file));
ifs.close();

// now you can swap
std::swap(file[2], file[5]);

// load new array into file
std::ofstream ofs{ file_name, std::ios_base::trunc };
if (!ofs.is_open())
    return -1; // or some other error handling
std::copy(file.begin(), file.end(), std::ostream_iterator<std::string>(ofs, "\n"));

Upvotes: 1

Ervin Szilagyi
Ervin Szilagyi

Reputation: 16815

WARNING: This will overwrite your original file!!!

#include <fstream>
#include <vector>
#include <string>

int main()
{
    ifstream in("in.txt");
    if (in.is_open())
    {
        std::vector<std::string> content;
        for (std::string line; std::getline(in, line); )
        {
            content.push_back(line);
        }
        in.close();
        std::iter_swap(content.begin() + 2, content.begin() + 5);

        ofstream out("in.txt");
        if (out.is_open()) {
            for (auto i : content)
            {
                out << i << std::endl;
            }
            out.close();
        }
    }
}

Upvotes: 0

Related Questions