I need to validate that a text file is in CSV format (i.e. that each digit is separated by a comma).
From reading online, it seems that people have conflicting views about it – but is Strtok() the best way to do this?
Any help would be great.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Your input seems so easy that I would probably just use a loop around
fgetc(3); I’ll sketch some pseudo-code here:You’ll have to manage the input in the functions in a manner that may be a bit awkward if you’re used to higher-level languages such as Ruby or Python where you’d just run
line.split(',')to get a list of numbers, but that is pretty idiomatic C.Of course, if this were a real problem, I’d probably prefer
flexandbison, and write a tiny lexer and grammar, mostly because it would be a lot easier to extend in the future as needs change.Update
With some additional criteria to check, the
handle_{digit,comma,newline}()routines are easier to sketch. I’ll sketch using global variables, but you could just as easily stuff these into astructand pass them around from function to function:Add whichever checks you need to validate the contents according to whichever rules you have. You might wish to standardize the order and contents of the tests to ensure that you never forget one, even if it means you write a
/* nop */comment once or twice to remind yourself that something is fine.