简体   繁体   中英

Algorithm for taking data in efficient way

I have one binary file which I have created. In it, data is stored in binary form but I will show it in human readable form like ;

[someOtherData]opalgo$apollo$[someOtherData]
               ^
               ^
               ^
             file pointer

I want hold that data "opalgo" in temp_S, which is declared as string.To note, not shown at example, I don't know what data is this place and its length.

To take data reside in binary file ;

  • First, I have calculated its length by incrementing file pointer and each time, I did comparison with '$'.
  • Second, I come back by length of data, for this case |opalgo| = 6.
  • Third, each time, I take one char and concatenate it with string, which is initialized with "" . that is, string += temp_Char ;

Above algorithm is mess, of course in my opinion. I couldn't find efficient way to take data from binary file. Now, I am a bit ashamed. Can you give me a better way ?

EDIT: I don't know file size, but as you know, I can calculate by using seekg and tellg.

Instead of doing it in three steps, it could all be done in the first: While looking for ther terminating '$' just put the characters into temp_S . No need to calculate length.

std::ifstream input(...);

std::string temp_S;
char c;
while (input.get(c))
{
    if (c == '$')
        break;  // Found terminator, read no more into string
    temp_S += c;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM