1

I wrote some code in order to double space a file in C++, currently the program takes in one file and returns a different file, that is double spaced. I want the program to return the same file to the file directory. I'm pretty at this point I need to a use a temporary file, which is fine, but I would like to at the end of the program eventually return the same file(but double spaced to the user). Any help would be appreciated. Here is my code thus far.

#include <fstream>
#include <iostream>
#include <cstdlib>

using namespace std;


int main( )
{
ifstream fin;
ofstream fout;

fin.open("story.txt");
if (fin.fail( ))
{
    cout << "Input file opening failed.\n";
    exit(1);
}

fout.open("numstory.txt");
if (fout.fail( ))
{
    cout << "Output file opening failed.\n";
    exit(1);
}

char next;
int n = 1;
fin.get(next);
fout << n << " ";
while (! fin.eof( ))
{
    fout << next;
    if (next == '\n')
    {
        fout << endl;

    }
    fin.get(next);
}

fin.close( );
fout.close( );

return 0;
}

2 Answers2

0

As you suggest, create a temporary file and then, only when processing has been successful, remove the existing file and rename the temporary file.

By the way, putting using namespace std at the top of every program is a bad habit that you'd do well to avoid.

Community
  • 1
  • 1
Edward
  • 6,964
  • 2
  • 29
  • 55
  • I have too always do "using namespace std" unless started with biger projects, for simple hello worlds programs is probably OK to use the whole std namespace, we all did that when started learning C++ :) – codekiddy Jul 26 '14 at 01:21
  • @codekiddy: better choice might be to something like `using std::cout;` to just pull in what you're really going to use. – Edward Jul 26 '14 at 01:23
0

Simplest solution: delete the input file and rename the new one (remove and rename)

Better solution: open the first file for both reading and writing (fstream) and replace the content with a stringstream buffer without even creating a temporary file (also faster).

You have plenty of choices.

Marco A.
  • 43,032
  • 26
  • 132
  • 246
  • 1
    You say better, I say faster but less atomic (if the flush to disk fails, or your program terminates during write-out, your SOL because you were writing to the same file). Depends on which is more important to you. – aruisdante Jul 26 '14 at 00:33
  • I would agree, in general I prefer to avoid relying on files (not even in temp directories) being in a directory or having to set up OS-specific facilities (e.g. existence checking) in order to work with them. – Marco A. Jul 26 '14 at 08:54