Archived

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

KevinG

Binary File I/o question...

Recommended Posts

KevinG    170
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
porthios    130
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
brassfish89    122
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   
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