Archived

This topic is now archived and is closed to further replies.

File Input - # of lines

This topic is 4987 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Is there any way to check the number of lines in a file and return it as an integer? I could run some test with Getline, but that would take up a lot of time, and the lines could be in the thousands. Edit- In C++, sry, keep forgetting that this is general. [edited by - DannyB on April 21, 2004 9:44:36 AM]

Share this post


Link to post
Share on other sites
The only way i know to achieve this is parsing all the file and counting lines like this

std::ifstream file("file.txt");
std::string buf;
int count = 0;

std::getline(file, buf);
while(!file.eof())
{
count++;
std::getline(file, buf);
}

std::cout << count << std::endl;
file.close();


maybe there''s a better way to do it, but it''s the only one I can think of

hope that helps !
Matt

Share this post


Link to post
Share on other sites
I don''t think there''s any way better than simply reading in the file in large chunks and counting the number of newline characters. Reading a file in large chunks is faster than reading it one byte at a time. For example:
int GetFileLines(char *filename)
{
int count = 1, i, gcount;

char buffer[1024];

ifstream in;

in.open(filename);

if(!in.is_open())
return -1; // Error


while(!in.eof())
{
in.read(buffer, 1024);

gcount = in.gcount();

for(i = 0; i < gcount; i++)
{
if(buffer[i] == ''\n'')
count++;
}
}

return count;
}

Share this post


Link to post
Share on other sites
quote:
Original post by Aprosenf
Reading a file in large chunks is faster than reading it one byte at a time.


Except that most implementations do this behind the scenes, at least in the case of fopen/fgetc/fclose.

Personally I think lemurion''s example is the best because it''s not platform-dependant. There''s no room for algorithmic improvement, so which implementation is fastest comes down to splitting hairs or profiling.

Share this post


Link to post
Share on other sites

std::ifstream input("file");
std::stringstream str;
str << input.rdbuf();
std::string file = str.str();
std::cout << std::count(file.begin(), file.end(), input.widen(''\n''));


Something like that??

Share this post


Link to post
Share on other sites