August 21st, 2003, 04:35 PM
Using fscanf to read a file one line at a time
This is straight C, not C++ or MFC. I want to know and how I can use fscanf and fputs to read a data file without determining the length. Here is what I am talking about.
My data file is in the form of
Now, it will be easier to do if I allow user to enter the length of the data, but I don't want that. I simply want user to enter the file name.
I would like to put fscanf inside a while loop and increment a counter for each line. After the end of the last line, I want to use malloc to allocate space for an array and put the value to that array. I want to know if it is possible and how I can do it.
August 21st, 2003, 05:20 PM
Sure you can do it.
But you should probably not use any scanf() function in any serious application!!!
If you know how to read in a float or double value from the keyboard, you should easily findout how to do it from a file.
Hint: %f or %lf
NOTE: scanf format codes work a bit different than printf's on floating-point numbers
Last edited by j0nas; August 21st, 2003 at 05:31 PM.
August 21st, 2003, 06:29 PM
I was think creating a dummy buffer to initialize like
then allocate memory of 2 for it, then every time I read a new line, I realocate by the counter.
The problem is I have to read each and save it to a buffer or array.
August 22nd, 2003, 03:39 AM
August 22nd, 2003, 04:16 AM
Yepp, you can reallocate space each iteration (but it may not be the best method)...
Use realloc()... something like this:
float *x = NULL;
int i = 0;
x = realloc(x, i + 1);
} while (fscanf(stdin, "%f", &x[i++]) == 1);
printf("Got %d rows of floats.\n", i);
August 22nd, 2003, 08:50 AM
Do you think of a better method rather than reallocate for each iterator?
August 22nd, 2003, 09:31 AM
You have many options, like:
1. Precount rows in file, rewind the file and then allocate exact number of rows
2. Using a linked list
3. Allocate a fix number of array entries (with malloc) and let it grow if needed
I would probably go for number 3 in this case...
August 22nd, 2003, 09:55 AM
I understand number 3 and I probably go with it, but I like the idea of precount the number of row in the file. Do you know how can I do that inside a while loop? Is there any way you can show me how to do it with a snap code?
August 22nd, 2003, 10:12 AM
Method 1 requires a file (impossible on stdin)... so you basically do: (untested code)
Going through the file twice may or may not be a performance hit. If the file is still in the cache, it may not....
for (rows = 0; fscanf(in, "%f", &f) == 1; rows++)
x = malloc(rows * sizeof(float));
for (i = 0; i < rows; i++)
fscanf(in, "%f", x + i);
August 22nd, 2003, 10:33 AM
Thank you, this is the first time I see and heard the rewind function, I have never use it. By looking at its description from MSDN, it makes a lot of sense.
Base on what you said, I don't need while loop. The for loop should do it.
Click Here to Expand Forum to Full Width