简体   繁体   中英

C number of line in the file (UNIX)

I'm trying to find the total number of lines in a text file, but it's not working (the final line count is 0 - see below). Here's the code:

#define BUFFER_SIZE 1
int lineNumber = 0;
int columnNumber = 0;
char *byteCurrent;
while (read(openFile, &byteCurrent, BUFFER_SIZE) > 0)
{
        if (byteCurrent[0] != '\0') columnNumber++;
        if (byteCurrent[0] == '\n') lineNumber++;
        printf("%c", byteCurrent);
}

在此输入图像描述

You have many problems with this code. The first is that you have an uninitialized pointer byteCurrent , but that doesn't matter since you don't actually use what it points to (which is just some seemingly random location) but you use a pointer to the pointer . When you do &byteCurrent you get a pointer to the variable byteCurrent which is of type char ** .

That's just one problem, another is that there is no string terminator in a file. If you get a zero when reading (which is what '\\0' is) it's because there is an actual zero in the file, not because you get to the end of something. This leads columnNumber to count the number of characters in the file and not any column number.

The solution to the first problem is to use a plain char variable:

char byteCurrent;

The solution to the second problem I don't know, because I don't know what your columnNumber variable is supposed to count.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM