Jump to content
  • Advertisement

Archived

This topic is now archived and is closed to further replies.

KevinG

Binary File I/o question...

This topic is 5319 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Is it inefficient to read a file one character at a time? Let''s say I wanted to read a line of binary data. Instead of reading it one character at a time, is there a way to just read the entire line? As in: char * c_ptr = (the line I just read from the file); If you could do this, would it be faster? Or would it be the same speed a reading the characters one at a time?

Share this post


Link to post
Share on other sites
Advertisement
char* fgets(char* string, int len, FILE*);

Get's a string for you, but you have to supply the number of characters. Maybe this might be a bit better:

int fscanf(FILE *stream, const char *format [, argument ]... );

And use it along these lines:

char* string = NULL;
fscanf(file, "%s\n", string);


That will only read a string up to the first whitespace character though. Im not quite sure how to avoid spaces with that. I believe you need to use square brackets, please correct me if Im wrong:

char* string = NULL;
fscanf(file, "%[]s\n", string);


[edited by - porthios on January 24, 2004 7:30:44 PM]

Share this post


Link to post
Share on other sites
Great. Thanks. BTW, are there any C++ equivalents to that? (Looks like C to me)
If not I''ll just use those.

Share this post


Link to post
Share on other sites
When you say 'line of binary data', do you mean it ends in a newline, or some other character? You could probably read in x characters at a time, which would probably be better than reading in 1 at a time. I'm sure you could create a dynamic buffer the length of the line (using istream::seekg) but I don't think it would be worth it.
EDIT:
Just so you know, porthios's code will not work due to the fact that he didn't initialise string. And here's the basic algo for my first idea:
loop
read in x number of bytes
if line terminator in buffer
replace line terminator with '/0'
move the read position back bufferlength-position of terminator
break out of loop

[edited by - brassfish89 on January 24, 2004 8:59:35 PM]

Share this post


Link to post
Share on other sites
Guest Anonymous Poster
A common approach to binary files is to read all the data into a buffer with a single call to fread().

Share this post


Link to post
Share on other sites

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!