How to write strings to a binary file

With this code, I tried to print the string "foo" 10 times in binary format. But why does the function not work?

#include <iostream>
#include <fstream>
using namespace std;

template <typename T> void WriteStr2BinFh (string St, ostream &fn) {
     for (unsigned i = 0; i < St.size(); i++) {
         char CStr = St[i];
         fn.write(&CStr.front(), CStr.size());
     }
     return;
}

int main() {
   string MyStr = "Foo";
   ofstream myfile;
   myfile.open("OuputFile.txt", ios::binary|ios::out);

   // We want to print it 10 times horizontally
   // separated with tab

  for (int i = 0; i < 9; i++) {
      WriteStr2BinFh(Mystr+"\t", myfile);
   }

   myfile.close();   
}
+3
source share
4 answers

There are so many errors here, I’ll just list everything I see:

Your condition for the loop should be i <10.

Why are you using a template, but not a template parameter T?

You call the front () method on CStr, but CStr is a char, not a string, so I don’t even know how this compiles.

Assuming CStr was a string, you don't want to take the address of the front () iterator with &, instead you want to say something like:

fn.write(St.c_str(), St.size());

And you do not want a loop for iterations of St.Size (). Just do it.

+9

omg, :

  • int main - ;
  • < typename T > ;
  • Mystr - , ++ case;
  • char CStr - front std::string ;
  • , , ;
  • , std::string ;
  • ;
  • ...

, :

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

void WriteStr2BinFh( const std::string& St, std::ostream &out ) 
{
    out.write( St.c_str(), St.size() );
}

int main() 
{
    std::string MyStr = "Foo";
    std::ofstream myfile( "OuputFile.txt", std::ios::binary | std::ios::out );


    for (size_t i = 0; i < 9; ++i) 
    {
        WriteStr2BinFh( MyStr+"\t", myfile );
    }

   myfile.close();   
   return 0;
}

std::fill_n

std::fill_n( std::ostream_iterator< std::string >( myfile, "\t" ), 10, MyStr );
+3

-, char CStr , CStr . -, fn.write(&CStr.front(), CStr.size()); , std::vector<>, , , .

, WriteStr2BinFh , , WriteStr2BinFh:

void WriteStr2BinFh(const string& St, ostream &fn)
{
    for(string::iterator it = St.begin(); it != St.end(); ++it)
    {
        fn.put(*it);
    }
}

,

void WriteStr2BinFh(const string& St, ostream &fn)
{
    fn.write(St.c_str(), St.length());
}
+1

io :

  • ios:: out ( ) ios:: ( )
  • write . char * , - int, , .
  • .

    void write_to_binary_file(WebSites p_Data)
    {
        fstream binary_file("c:\\test.dat",ios::out|ios::binary|ios::app);
        binary_file.write(reinterpret_cast<char *>(&p_Data),sizeof(WebSites));
        binary_file.close();
    }
    

    / .

  • ios:: out ios:: binary. ios:: app, , . , .

  • The write function used above needs a parameter as the type of a character pointer. Thus, we use the conversion of the reinterpret_cast type to give the structure a structure of type char *.

+1
source

Source: https://habr.com/ru/post/1705387/


All Articles