开发者

How to find number of lines of a file?

for example:

file_ptr=fope开发者_运维百科n(“data_1.txt”, “r”);

how do i find number of lines in the file?


You read every single character in the file and add up those that are newline characters.

You should look into fgetc() for reading a character and remember that it will return EOF at the end of the file and \n for a line-end character.

Then you just have to decide whether a final incomplete line (i.e., file has no newline at the end) is a line or not. I would say yes, myself.

Here's how I'd do it, in pseudo-code of course since this is homework:

open file
set line count to 0
read character from file
while character is not end-of-file:
    if character in newline:
        add 1 to line count
    read character from file

Extending that to handle a incomplete last line may not be necessary for this level of question. If it is (or you want to try for extra credits), you could look at:

open file
set line count to 0
set last character to end-of-file
read character from file
while character is not end-of-file:
    if character in newline:
        add 1 to line count
    set last character to character
    read character from file
if last character is not new-line:
    add 1 to line count

No guarantees that either of those will work since they're just off the top of my head, but I'd be surprised if they didn't (it wouldn't be the first or last surprise I've seen however - test it well).


Here's a different way:

#include <stdio.h>
#include <stdlib.h>

#define CHARBUFLEN 8

int main (int argc, char **argv) {
    int c, lineCount, cIdx = 0;
    char buf[CHARBUFLEN];
    FILE *outputPtr;

    outputPtr = popen("wc -l data_1.txt", "r");
    if (!outputPtr) {
        fprintf (stderr, "Wrong filename or other error.\n");
        return EXIT_FAILURE;
    }

    do {
        c = getc(outputPtr);
        buf[cIdx++] = c;
    } while (c != ' ');
    buf[cIdx] = '\0';
    lineCount = atoi((const char *)buf);        

    if (pclose (outputPtr) != 0) {
        fprintf (stderr, "Unknown error.\n");
        return EXIT_FAILURE;
    }

    fprintf (stdout, "Line count: %d\n", lineCount);

    return EXIT_SUCCESS;
}


Is finding the line count the first step of some more complex operation? If so, I suggest you find a way to operate on the file without knowing the number of lines in advance.

If your only purpose is to count the lines, then you must read them and... count!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜