Efficiently write in a file in C++ I've made a program which reads from the console and writes it in a .txt file. This programm should write in a file with \n.
#include &lt;iostream&gt;
#include &lt;fstream&gt;
#include &lt;string&gt;

using namespace std;

int main() {
    ofstream fich(&quot;file.txt&quot;);

    if (!fich)
        cerr &lt;&lt; &quot;Error!\n&quot;;

    char fst = 'l';
    string c;
    while (fst != '\0') {
        getline(cin, c);
        fst = c[0];
        fich &lt;&lt; c &lt;&lt; endl;
    }

    fich.close();

    return 0;
}

This program ends when the user inputs nothing and then a \n, because, doing that, the string c will only have a \0 end of string element.
I was wondering if there is any way of doing this more efficiently, maybe without needing a &quot;void \n&quot; line to finish the program.
Error Handling
You check whether the output file was opened correctly, but all you do is output a message (you don't even say what's wrong!) and then you keep on ignoring it. What if file.txt is a directory or read-only? I guess you haven't tested these cases. By default, throw an exception if you can't continue at some point. In this case, throw std::runtime_error(&quot;failed to open output file&quot;).
Loop Condition
You are reading until the line is empty. This is okay-ish, but why don't you just check whether c.empty() and then break from the loop? Another case is that the end of the input is reached. In that case, the streamstate is set to failed. I'm not sure what happens in getline() then (read the docs at cppreference.com), but if it just doesn't change the string passed by reference, you may end up in an endless loop.
As an alternative I would use getline(cin, c) as loop condition. If this succeeds, you have received a line which can then write to the output file. Otherwise, you either had an error or you reached the end of the input.
Closing Filestreams
If you didn't call fich.close(), when would it be closed? However, consider the possibility that the file can't be written fully. You'll never notice this, neither with your code nor if you let the destructor do its work. So, what I'd rather do there is a call to fiche.flush() followed by a check of the streamstate.
Efficiency
I wouldn't bother with that at the moment. Point is, you're still learning to walk, so don't try to run yet. Still, what you're doing is inefficient. Firstly, writing in size of lines is useless, because you're just moving bytes from one file to the other. Secondly, endl implies a newline and a flush. So this is not really a cheap operation! In addition, there is a lot of stuff going on in C++ IOStreams that there's a whole book about their internals. Lastly, copying files can sometimes be done more efficiently using OS features which will avoid looking at the data more than necessary.