0

What's the difference with following codes:

Code #1: Using Binary Mode

int main()
{
    std::fstream w("D:\\file.txt", std::ios::out | std::ios::binary);

    char *p = "Hello World\r\nHi";

    w.write(p, strlen(p));

    // Close the file
    w.close();
}

Code #2: Using Text Mode

int main()
{
    std::fstream w("D:\\file.txt", std::ios::out);

    char *p = "Hello World\r\nHi";

    w.write(p, strlen(p));

    // Close the file
    w.close();
}

Does it matter whether I use binary or text mode in case of writing strings like this?

9
  • 1
    Since it looks like you're using Windows, in text mode '\n' gets written as the two characters '\r' '\n'. Commented Apr 22, 2019 at 2:06
  • 1
    The files will be different on windows because of the processing of \n. Look at it in a hex editor. Commented Apr 22, 2019 at 2:06
  • Yes, I am using Windows 8.1. Commented Apr 22, 2019 at 2:09
  • In my code, I am using w.write(.. for binary and text mode. Does it matter? Commented Apr 22, 2019 at 2:13
  • The duplicate question has C code not C++. Commented Apr 22, 2019 at 2:15

1 Answer 1

0

Basically, if you're working with text, bits represent text data, but in binary, bits represent custom data (not only text, but audio, image and etc). If you intend to work with text, I'd suggest you to use text mode, since it'll be less prone to get corrupted and easier to use with other applications.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.