How to do this in C

Soldato
Joined
1 Mar 2003
Posts
5,508
Location
Cotham, Bristol
This must be a pretty simple thing to do, but unfamiliar with the language say you have a txt file that is set up like a table and has a number of tab separated columns, the first column being the key you match against so:

key col1 col2 col3
=== === === ===
00 10 20 30
01 40 50 60
02 70 80 90
03 00 05 10
04 15 20 25

Now the function would be called something like this

Code:
char * string = readTable(path_to_table,retrieve_column,key);

So the key column is column 0, col1 is column 1 and so on, so if were to call the above function like so

Code:
readTable("C:\table.tab",1,"02")

Then the value returned would be 70. so the pseudo code is quite easy

readTable(path_to_table,retrieve_column,key)
open table(path_to_table)
read each line until key is matched
retrieve the value from passed column number

So C gurus, how would this be done. Btw this is to prove a point to one of my work colleagues, I said this would be pretty easy for a clever C programmer to knock up in less than half a day, he doesn't agree.

It can't be that hard can it?
 
Not overly hard:

To open the file would be simply 'fopen(path_to_table, "r")', and an fclose on the ptr at the end to clean up.

To read the lines i'd use something like fscanf, this reads in a line, with a given format/variable list to split up that line depending on the format and automatically store the values. Could just use an fread and parse it manually, or use strtok to split it based on string instead, kinda personal preference, but easy enough to get a set of strings representing each token on the line.

Could use the reading of the first line to do some error checking with the column value, but depends if the file is always a key and 3 columns or if it can vary, otherwise ignore the first 2 lines read.

Then as you said, read each line until the key is matched, the reading is as above, doing an atoi on the string would give the int value, or a strcmp if you want to pass in a string key, then pick the correct string for the requested column and either return the string or even another atoi to convert it to integer.

So easily doable in half a day, shouldn't take much longer than an hour really.
 
Back
Top Bottom