Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying to learn basic file manipulation in c++

Tags:

c++

I'm trying to get the hang of working with files in C++. I'm trying to read from one file and make another file with the same contents. I've succeeded to a point where I can get the first line of my file to get copied but not the rest. Can anyone tell me what I'm doing wrong?

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main(int argc, char * argv[]){

    string line;
    ofstream writeFile;
    ifstream readFile;
    readFile.open("students.txt");
    if (readFile.is_open()){
        while (getline (readFile, line)){
            writeFile.open("copytext.txt");
            writeFile << line;
            writeFile << line;
            writeFile << line;
            writeFile << line;
        }
    }
    readFile.close();
    writeFile.close();
    return 0;
}
like image 337
hackrnaut Avatar asked Jan 19 '26 16:01

hackrnaut


1 Answers

By default, if you don't specify a flag, the openmode is going to be write. This will destroy the contents of the file if it already exists.

#include <iostream>
#include <fstream>

int main()
{
    std::ofstream of("test.txt"); // close() implicitly called by destructor
}
> echo "hello" > test.txt
> cat test.txt
hello
> g++ test.cpp
> ./a.out
> cat test.txt

Oops!

You should obviously move it outside the loop. By the way, you don't need to call open or close explicitly, because the constructors and destructors will call those respectively. The stream objects will also be implicitly convertible to bool (returning false if there's an error in the stream), making is_open redundant.

int main(int argc, char * argv[]){
    string line;
    ifstream readFile("students.txt");
    ofstream writeFile("copytext.txt");

    if (readFile && writeFile){
        while (getline (readFile, line)) {
            writeFile << line;
        }
    }
}

Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!