Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

least error-prone C scanning

Status
Not open for further replies.

ielo

Programmer
Jan 22, 2004
15
CA
Hi,

I often use C for data handling, with the data being sent back and forth from someone else's parent program (so I rarely write my own read/write functions). I have to update what I consider an error-prone way of scanning and parsing a given file (known format).

I've gone through a number of posts in this forum on scanning/parsing text files with C functions. Usually, a newbie posts some first-try, and then others suggest good and not so good changes to the initial code. Sometimes, the low-level char-by-char manipulation seems to be one of the less error-prone ways of doing it.

I'd like to tackle this from another angle: has anyone come across well-written published C code that scans/parses and that has prompted one to say: "Now, that's the way to do it! Code to emulate for a newbie!". What I mean by 'published' is that it's actually found in a distributed program. Of course, anything open source GPL (most of Linux) would be appropriate as an example since the source code is accessible.
 
What type of data are you parsing? Is it free form numbers, fixed format stuff, letter sequences, xml etc?

The proper way to write a parser is to first create a scanner (lexical analyser). This is a simple state machine. What tools like lex do is to create the state machine for you. Pass the output of the scanner to a syntax analyzer to get your data. Of course if you just want the tokens, you can just stop at the scanner stage.
 
Using fgets() to get lines of file into buffer, and then using sscanf() to search the buffer is less error prone than just using fscanf(). But I suppose it does depend on what data you want to pass, as xwb pointed out...


Don't hate the player - hate the game
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top