Know the line number of a txt file in c

Asked

Viewed 8,101 times

2

Is there a function or way to find out how many lines a file has without opening it? I need to divide a file into two parts, so that two processes read it at "the same time". I will use the fseek() function to move the pointer to a certain position of the file, but I need to find out how many lines the file has to be split.

  • 1

    There is no universal way to find out how many lines a file has without opening it. In Unix and its derivations, you can use the stat or fstat command in C to find out what size in bytes the file is. With this, you can open the file in two processes, dividing by the size in bytes of the file. Even so, the recommended way to find out how many lines or how many bytes a file has is to open it and count the bytes or new line characters. You can use the fseek function for this.

  • Are the lines in your file all the same length? If you know how many bytes the file occupies (stat()) and divide by line size get the number of lines without opening the file.

1 answer

5


Without opening the file I believe that there is no way to get this information.

But if you use UNIX you can use the command wc to find the number of lines.

wc nomedoarquivo


If you decide to open the file, a way that I always use to scroll through the file quickly and count the number of lines is with this code:

while (EOF != (scanf("%*[^\n]") && scanf("%*c"))) 
    ++numLinha;

Browser other questions tagged

You are not signed in. Login or sign up in order to post.