binary mode

can anyone help me? how can we use endl in binary mode for files?
for expl.
fstream myfile;
myfile.open("test.txt",fstream::in|fstream::out|fstream::binary)
myfile<<"hi"<<endl<<"bye";
it won't go next line.....what should i do?

You shouldn't perform formatted output in binary files, what are you trying to do there?
i wanted to write address book program ,in binary mode i could move in my file easier(i think)
but when i want to input my string in the file,it dose not accept .....
closed account (4Gb4jE8b)
well to directly answer your question you might try "\n" as in

1
2
3
fstream myfile;
myfile.open("test.txt",fstream::in|fstream::out|fstream::binary)
myfile<<"hi\nbye";


however I agree with bazzy, you will likely come up with more problems trying to do it this way than using a series of strings or const char*
how can i give a string to a file,like char phonebook[2000] ,and after every 100 index it goes next line.(?)
i tried it,it dosen't work.my output in file was: hi bye
closed account (4Gb4jE8b)
at that point if you want to continue in binary, you are well beyond my area of expertise.

With strings however you could use a variety of options such as
MyString.rfind('\n',(character count))
and as for passing a string to a file, that too is only a few lines of code:

1
2
3
4
5
6
7
8
9
10
11
//untested code

#include <fstream>
#include <string>

ofstream myfile;
string mystring;
myfile.open("test.txt");         // include modifiers as needed
getline(cin, mystring);           //presuming you're entering the person by name, will not include the '\n' character, will include spaces, not sure about dashes
myfile << mystring;               // puts what you wrote into a file
myfile.close()
C++ is broken in this regard.

You cannot seek properly unless you are using binary file I/O.
But you don't get the convenient newline translation unless you are using textual file I/O.

There's a way to cheat, but it'll take me a short bit to figure it out.

For a not-so-great cheat, you could just use macros to check your OS and output the proper string that way.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include <iostream>
#include <sstream>

template <typename CharT, typename Traits>
std::basic_ostream <CharT, Traits> &
endl( std::basic_ostream <CharT, Traits> & outs )
  {
  #if defined(_WIN32)
    return outs << "\r\n" << std::flush;
  #elif defined(Macintosh)
    return outs << "\r"   << std::flush;
  #else
    return outs << "\n"   << std::flush;
  #endif
  }

#include <fstream>
using namespace std;

int main()
  {
  ofstream f( "foo.txt", ios::binary );

  f << "Hello world!" << endl;
  f << "Success?" << endl;

  f.close();

  return 0;
  }

Of course, this particular cheat only works if you use the modified endl to do newlines...

Sorry..
Topic archived. No new replies allowed.