views:

530

answers:

4

I'm copying over text from one file to another, with certain changes.

I have input.txt, tmp.txt and output.txt.

The idea is to copy a few lines over to tmp.txt (until we reach a delimiter), move the text from tmp.txt to output.txt, wipe tmp.txt and then continue the cycle until we reach the end of input.txt.

I'm having trouble with the tmp.txt file. After the first time I copy the contents over it stops accepting new text, even after I've closed, deleted and re-opened the file for writing. My code has become really messy.

Could anyone suggest a neat way of doing this? (coping to tmp.txt, copying from tmp.txt,wiping tmp.txt continuing the cycle)

Thanks in advance.

N.b. This is a subtask that I'm stuck on with a homework problem- I'm removing c++ comments from a text file.

Edit: For anyone wondering why I need the tmp.txt: If the program encounters */ (close comment) without an open comment then it will need to treat everything before it, until the previous comment, as a a comment. I'm using the temp to hold text that may or may not be a comment. If it is- I'll delete the text in tmp, if not, I'll copy the text in tmp to output.txt.

+1  A: 

If you are using the C++ fstream stuff, you may have to call .clear() on the stream when you re-open it in order to clear error flags (such as those set when you hit EOF).

ravuya
+1  A: 

I suggest you skip the tmp.txt file. Should be enough to just open input.txt and just shuffle data into output.txt as you see fit.

Magnus Skog
A: 

Unless it is part of your homework to actually do the comment deletion, i would suggest some simple scripting. Here is a reference to a sed script.

If the homework involves deleting the comments, you could just run the input file as a stream and stop writing the output file while in a comment.

  • You could start with detection of start and end of a comment,
    • Implement this for C style comments and the //, C++ style
  • Then, use a stack and scale up to detecting nested comments
    • Here, your understanding of nesting with both commenting styles will help
  • Finally, you could detect the #if 0 and #endif blocks -- just for kicks :-)
nik
+2  A: 

Open input.txt as an istream, and output.txt as a ostream. Start reading from input echoing all the characters not belonging to a comment. When you encounter a comment, don't write to the output. That should do it.

ferrari fan