I want to read all integers from a file and put them all in an array
./prog input.txt
where input.txt contains for example the following numbers
-6 8 9 0 45 54 67 0 12
2开发者_JAVA百科3 3 -25 12 67 6 9 -9
How to do this without knowing the number of integer in advance
thanks for anyone answer !
Something like this. (Not tested)
while(!feof(inFile)){ //inFile is your pointer to the file opened with fopen()
fscanf(inFile,"%d",&a[i]); //a is your array
i++;
}
This way in your i
variable you will have the number of items in the file (+1) and you'll get all numbers in the array.
- initialize a memory area
- read number in a loop and
- if needed use
realloc
on the memory area
- if needed use
- add number to array
- [use memory area]
- release memory
You will need to keep a count of how many elements are already in the array and the maximum number of elements it can have (so you know when it's time to reallocate).
精彩评论