File Reading

  • Thread starter cplusplusquestion
  • Start date
C

cplusplusquestion

I have a binary file like:

a bla bla bla bla
b 12 23 34 80 38

a bla bla bla bla
b 23 45 89 30 99

When I find first character of the line is 'a', I would like to skip
reading this line, then go to next line. Any suggestion?
 
I

Ian Collins

I have a binary file like:

a bla bla bla bla
b 12 23 34 80 38

a bla bla bla bla
b 23 45 89 30 99

When I find first character of the line is 'a', I would like to skip
reading this line, then go to next line. Any suggestion?

If it's a binary file, how do you know where the next line begins?
 
E

Eric Pruneau

Ian Collins said:
If it's a binary file, how do you know where the next line begins?

From what I see, you can do:

1. read a char until you get a number
2.read a char until you get a letter

do this steps util the end of file

here a way to do this (with little error checking), you can test it with a
bin file like this one
a bla bla bla blab 12 23 34 80 38a bla bla bla blab 23 45 89 30 99

it can be on a single line, it doesn't matter.



bool isNumeric(char tmp)
{
return tmp >= 48 && tmp <= 57; // from ascii table
}

bool isLetter(char tmp)
{
// from ascii table
return (tmp >= 65 && tmp <= 90) || // A-Z
(tmp >= 97 && tmp <= 122); // a-z
}

int main()
{
std::ifstream ifs("FileName.bin", ios_base::in | ios_base::binary);

string linea , lineb;
while(ifs)
{
// now read a line and b line
char tmp=0;

while(!isNumeric(tmp))
{
ifs.get(tmp);
if(ifs)
linea.push_back(tmp);
else
break;
}
int bpos = linea.rfind('b');
lineb.assign(linea,bpos,linea.size()-bpos);
linea.erase(linea.begin()+bpos, linea.end());
// now you do your stuff with linea

while(!isLetter(tmp))
{
ifs.get(tmp);
if(ifs)
lineb.push_back(tmp);
else
break;
}
// ok I assume the data in linea has been extracted and stored elsewhere
so I can clear the string
linea.clear();
size_t apos = lineb.rfind('a');
if(ifs)
{
linea.push_back('a');
lineb.erase(lineb.begin()+apos, lineb.end());
}
// now extract info from lineb ....
lineb.clear();
}

return 0;
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top