I've spent hours, an embarrasing number of HOURS on how to read a text file into a program. The requirements have shifted, but still. I hate you C. You and all your pointers.

The text file is a matrix, but with the first line being the number of rows. See example below.

matrix_c_is_evil.txt

11                // int number of rows
a1 a2 a3 b1       // double (these can be negative)
...
a33 a34 a35 b11

I have read a lot of stuff. And I guess I'm tired, because it all seems to cirlce back to the same stuff that doesn't work. Does fscanf not work with negatives? I'm having a hard time confirming this.

Do I have to read in the entire file, then parse by fgets or fgetc (or whatever the individual char function is)?

Why is this such a pain in the donkey? If it were integers it seems like it would be a lot easier.

I assume your values are separated by commas?
Did you ever try to google "How to read CSV file in C"?

If you show us your code, we can offer advice on improving it. For now, I can only answer your questions.

Does fscanf not work with negatives?

It works fine, provided you use a signed format specifier like "%d".

Do I have to read in the entire file, then parse by fgets or fgetc (or whatever the individual char function is)?

Probably. I say this because each line represents a row of the matrix, and fscanf will not tell you when it reaches a new line. All whitespace is equal where fscanf is concerned.

Why is this such a pain in the donkey? If it were integers it seems like it would be a lot easier.

My guess is it's a pain because you're trying to match a series of lines in the file to rows in an array. I strongly doubt this would be alleviated by storing integers in the file rather than floating-point. It's really a parsing problem, not a data representation problem.

This article has been dead for over six months. Start a new discussion instead.