What is the most elegant way to write a text / binary using C ++?

I found good reading results, for example: Read txt with iterators and preallocation or read in containers . So I wondered how to write the most elegant std :: string to a file?

Edit: when reading, I can pre-allocate space for the line using seek and tellg, since I know the size of the line, how can I tell the file system how much I want to write?

+3
source share
3 answers

Here is a tiny example of how to output std::string, but you really need to read fstream

#include <iostream>
#include <fstream>
#include <string>

int main(int argc, char *argv[])
{

  std::string s("writemeout");
  std::ofstream outfile("output.txt");
  if(!outfile.is_open()) {
    std::cerr << "Couldn't open 'output.txt'" << std::endl;
    return -1;
  }

  outfile << s << std::endl;
  outfile.close();
  return 0;
}
+6
source

operator<< std::ofstream. :

#include <fstream>
#include <string>

int main() {
    std::string s( "Hello, World!" );
    std::ofstream f( "hello.txt" );
    if ( !f.fail() )
        f << s;
}
+1

, .

std::ofstream ofs; // presumed open
ofs << v1 << v2 << v3 << v4 << v5; // some different variables
ofs.close();

std::ifsteram ifs; // open to same stream
ifs >> r1 >> r2 >> r3 >> r4 >> r5; // variables of same types as above

, , , , . , , , , .

, , .

"" , , , . iostream:

os << str.size() << str;

, , , .

os << str.size() << '\t' << str;

.

, std:: getline . istream_iterator , - .

- , : - - .

, , , , .

. fwrite C, , , , , .

, : - Windows ASCII 13 ASCII 10, , . - , endian size, . - endian-ness , . , , , .

int x;
os.write( &x, sizeof(int) );

, - , .

, , - .

, .

boost .

, , . "" .

+1

All Articles