Question:
Need a little help with C?
rettix
2008-03-12 20:17:58 UTC
Hi, I am writing a program that is reading from a .dat or .txt file with 250 columns and 4000 rows. I am creating linked lists to handle all of the data, but my problem is coming from actually reading the data in.

What i would like to do is have 250 nodes of one type of linked list. So, my question is how do I read in just one line at a time while still capturing each set of numbers from each line? So I can reset my main linked list back to the root node when I reach the end of the line. For example, I want to have 250 nodes for the main list, and then have 4000 nodes in another linked list stemming from each of those 250 nodes.

This is what I am using to read from the file:

while( fscanf( input, "%lf", &data) == 1){

//do stuff

}

And of course as you can imagine it doesn't recognize line breaks. It just continues to create new nodes until the end of the file. Hope this makes sense.
Three answers:
Craig R
2008-03-12 20:52:55 UTC
Use fgets() to get a line.



Write a function that splits the line into 250 nodes in your linked list by searching for a space (strchr() IIRC) or the end of line.



Repeat until you're out of data.



Since your lines all have a fixed number of columns, consider putting all the data from one row into an array, then having a linked list of row arrays.



If you always have 4000 rows, consider using a two-dimensional array for the whole thing and skip the linked list which is just adding complexity.
gene_frequency
2008-03-13 03:31:46 UTC
look up usage of fgets()



fgets() reads up to and including the end of line character...and stops. Call fgets() multiple times to read a file one line at a time until fgets() returns NULL. It's a champ...



Now, your next natural question mite be then what? OK, you've got a buffer filled with one line of data from the file...parse the buffer to pull the data. If the Excel file is CSV (comma delimited format), then pull the data between commas....



Of course, there's more to it than this, and u can let your code grow toward perfection by starting with the simple. I've been massaging my Excel CSV format file-reading code for years. There's probly something I'm still missing after all this time. But you reach a point where it works-as-advertised, and you let go.



Like, did you know that, in CSV format, if there's a comma *in* the data, then that data is put in quotes. That's how Excel knows the comma is _not_ a field separator. Oh yea...



I'm looking forward to your next new question if you need more help....
2008-03-13 03:22:18 UTC
I'd slice the data the other way - do it based on rows. Use getchar() instead, so that you can grab the entire line at once. Then each line can be a linked list, and the entire data structure is a linked list of 4000 elements, each of which is a linked list of the data in each row.


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...