Writing to file causing weird characters to appear at end.

I'm trying to write a string to an empty file. The string is succesfully written, but what confuses me is why the program adds hundreds of weird characters to the end of the file. These strange characters cause the program to throw the following error whenever it reads from the same file later on:
File: f:\dd\vctools\crt_bld\self_x86\crt\src\isctype.c
Line: 56
Expression: c >= -1 && c <= 255


The output file looks like this, but with many more of the same odd character repeated over and over:
Test Name
Test StringÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍ


Here is the code printing to the file:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
void Write(std::string &str1, std::string &str2, std::fstream &file){
    file.clear();
    file << str1 << "\n" << str2 << "\n";
}



//in main function
std::fstream file;
file.open("test.txt", std::fstream::app);
std::string str1 = "Test Name";
std::string str2 = "Test String";

Write(str1, str2, file);

file.close();


Note that if I omit file.clear(); then nothing is ever written, because I read from the file first, so I have to reset the eof flag in order to write to it again.
Last edited on
Don't ever reuse a fstream object when it has already completed its job.

Why not?

But you can at least call close() method and reopen the file again with different attributes.

But realize that just closing and reopening a stream doesn't always clear any stream errors. The original C++ standard didn't clear() the stream errors when re-using the streams.

Now to the original question/problem. I suggest you show more content, and note when dealing with an fstream() you should specify the complete open mode since the mode flag supplied in the second parameter overrides the default mode. From: http://www.cplusplus.com/doc/tutorial/files/

For fstream, the default value is only applied if the function is called without specifying any value for the mode parameter. If the function is called with any value in that parameter the default mode is overridden, not combined.


So if you want to use an fstream as an input and output stream with the app flag you should so specify: std::fstream stream(FileName, std::ios::in | std::ios::out | std::ios::app);

Topic archived. No new replies allowed.