Hey guys,
I am trying to write a section of a program that reads in data from a file and stores the data into an array. The problem is the length of the file can vary, and I need to know how many items to store in the array.(I really just need to know how many lines are in the file.) There are two ways I've thought of doing, I haven't tried either yet, but I'm looking for ideas at the moment.
The first way I thought of is just doing a do / while loop, and keeping it going as long as (end of file) has not been reached. But if I do that I can't declare the array before the loop and tell it how many items are going to be stored in it.
The second way is doing a short do / loop before I declare the array. It would look like :
do
ignore(entire line of the file)
numberOfLines++
if (end of file has been reached) then Break;
loop
Then declare the array like so :
int array[numberOfLines];
----------------------------------------------------
Any other ideas or reference material that would give me ideas would help. Thank you so much!

- Daniel
P.S. I'm trying to write it in the shortest amount of lines/characters possible

In <stdio.h> you can use fseek to move to the end of the file and then use ftell to see where you are at, then fseek to move you to the begining again.

If you are using windows GetFileSize (handle). This method doesn't require you to move to be begining of the file as in the previous method.

<iostream> also provides you with similar methods, but I don't know those right off.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.