size of a text file

hi

need to find a way of reading how many 32-bit numbers are in a text file i am opening the file and the putting the content into an array[].

e.g.
there is seven 32-bit numbers in the file but i don't want to count them manually

text file contains

757935403 544999979 175906848 538976380
757795452 170601773 170601727
I don't think there are any other ways than counting them manually (using a loop). Can't you use an std::vector that will resize itself automatically instead of a fixed sized array?
thanks for the help
Yeah, you need to manually test how much was read.

C++ iostreams are great!

Code tested with VS2008.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#include <iostream>
#include <fstream>
#include <vector>

using namespace std;

int ReadFile(const std::string & fileName, vector<int> & output)
{
    int intBuffer;
    int numIntsRead = 0;
    ifstream inFile(fileName.c_str());

    while(!inFile.eof())
    {
        inFile >> intBuffer;
        // stream ok?
        if(!inFile.fail())
        {
            ++numIntsRead;
            output.push_back(intBuffer);
        }
        else
            break;    // probably redundant considering while condition
    }
    return numIntsRead;
    // or use this and eliminate the local "numIntsRead"
    return output.size();
}

int main(void)
{
    string myFile = "C:\\Temp\\numbers.txt";
    vector<int> myFilesInts;
    int myFilesIntsCount = ReadFile(myFile, myFilesInts);
    cout << "Read " << myFilesIntsCount << " integers from file." << endl;
}


Topic archived. No new replies allowed.