简体   繁体   中英

using ofstream writes binary without the ios::binary flag C++

I have a few std::vector of length N with long, string, double types. I am trying to write it to a plain text file this way:

int N = 100;
std::vector<std::string> var1String(N), var2String(N), var3String(N), var4String(N);
std::vector<long> var1Long(N);
std::vector<double> var1Double(N);

...

 std::ofstream f(path2file);
      for(int i=0; i<N; i++)
    {
f << var1String[i] << " " << var2String[i] << " " << var1Long[i] << " " << var3String[i] << " " << var1Double[i] << " " << var4String[i] << std::endl;
}

although I am not using the ios::binary flag it gets written in binary which I can easily read in linux. However I want to write it into a plain ASCII text file. (Note: I've also tried converting the var1Long[i] and var1Double[i] to strings without making any difference). What am I doing wrong?

EDIT: It is part of a larger program that gets some outputs from a server to the vectors in ASCII. As I said, when reading teh binary with linux or running the program using std::cout instead f it prints just fine. I just do not understand what might be causing the stream to be passed as binary.

What do you think ios::binary does?

As explained by Nick Bedford in « What's the difference between opening a file with ios::binary or ios::out or both? »:

ios::binary makes sure the data is read or written without translating new line characters to and from \\r\\n on the fly. In other words, exactly what you give the stream is exactly what's written.

It does not mark a file for binary content, it just keeps from translating C new line to their textual representation. Its absence does hence not prevent a file from containing binary data.

In short: you get binary data in your file because your "string" variables do contain binary data.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM