Home > Net >  Is it okay to read text files as binary?
Is it okay to read text files as binary?

Time:04-02

I am working on GLSL shader program loader. The shader programs are just plain texts with source code inside. I can open them by calling fopen() in binary mode, it is much easy. But as my source files are texts, should I proper use fopen() as for working with text files called without binary flag and read them line by line? Which is more tedious to concatenate whole text line by line, and line buffer lengths getting capped being read by fgets(). So if there any line longer than buffer, the read would be failed. But programs… They are text files by the way… What the disadvantages of reading text files in binary mode? May be encoding or line ending issues will come up? What should I do? Should I read them in binary mode, or text mode though?

CodePudding user response:

You should open the file in text mode if you're going to process it as lines. Text mode automatically converts the operating system's line break character to \n. So on Windows, the \r\n sequence will be translated to \n, and fgets() will use \r\n as the line delimiter; on Unix the newline character is already \n, so no translation is needed, and there's no difference between binary and text mode.

CodePudding user response:

The binary / text flags to fopen are just about newline conversions. binary just passes through newlines as is, text will convert newline sequences common to the OS the program is running on, to simple \n single byte newlines. The GLSL compiler doesn't care at all about what kind of newline (Unix style \n, Windows/DOS style \r\n, RISC OS style \n\r) it sees, it's all whitespace to it, anyhow.

Also there's no need to present OpenGL with split lines. That glShaderSource takes an array of strings is meant as a convenience, so that you can have some common shader strings, that you put as a header or similar into the source string vector. But just supplying a single long string is perfectly fine.

CodePudding user response:

I am presented with "what is appropriate for the expert is not appropriate for the novice." If you want to proceed, here is your path:

  • Get told No
  • Try to do it
  • Learn why not
  • Adapt
  • Learn
  • Develop the library that is a mirror image of the input libraries
  • Discover the No has become yes.

Or are just copying files? If so, no problem. Open and copy away.

In the old days we had this thing about text files; you got your platform's behavior on opening them and when copying files between systems you had to convert line endings.

Those days are passing away; everybody is abandoning fopen in text mode and just accepting any line endings using a simple state machine.

  • Related