LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Read binary file line by line (https://www.linuxquestions.org/questions/programming-9/read-binary-file-line-by-line-938246/)

shamjs 04-05-2012 04:33 AM

Read binary file line by line
 
Hi all,

please let me know how to read an binary file line by line ,i dont have problem in reading by making use of buffer,but i need to read an .bin file line by line a sample code will help me a lot








waiting for your inputs.........

jf.argentino 04-05-2012 06:23 AM

How do you define a line? If it's some data ended by character "\n" (or "\r" or both), there's no line in a binary file!

uhelp 04-05-2012 07:25 AM

Like jf.argentino already said: By definition there is no such thing as a line in binary files.
In a binary file a newline can occur everywhere.
But it must not define a newline, it could be as well just a digit having the same value like a newline.
That's why the two modes (binary/text) to read/write a file exist.

If want that weird thing anyway, you have to write your own routine to get newline delimited chunks of a binary file.

What are you really trying to do?

ta0kira 04-05-2012 08:12 PM

The newline thing can be dealt with; what can't be dealt with using C-strings is \0. You can certainly read up to the newline, but you need to know how long the input is in case there is a \0 in there. I generally consider "text" to be data with only non-\0 characters, and "binary" to be data with any character.
Kevin Barry

Nominal Animal 04-06-2012 02:02 AM

Quote:

Originally Posted by ta0kira (Post 4645919)
I generally consider "text" to be data with only non-\0 characters, and "binary" to be data with any character.

Me too. Fortunately, in C99 you have getline() and getdelim() that handle arbitrary-length lines or binary data, by way of returning the explicit number of bytes read. Thus, the data is not really C strings, but character arrays. (The functions will still add an extra NUL (\0) after the data, so you can treat the buffer as a normal C string if you wish.)

Still, what you said does apply: the string functions will only consider the data up to the first NUL (\0) byte. GNU C library does provide a few extra functions, such as memmem(), memchr() and memrchr(), to handle such data correctly.


All times are GMT -5. The time now is 10:36 PM.