wc 命令是否会从 txt 文件中去除尾随换行符?

0 command-line terminal wc

我目前正在构建wc命令行调用的副本(在 C 中)。我有一个文件 [tst.txt]文件 以及读取该文件的 C 代码。该wc tst.txt命令以输出作为响应:2 6 20 tst.txt,表示 2 个换行符 ('\n')。但是,我的代码计算了 3 个换行符。我假设这是由于文件末尾的系统尾随新行(第 3 行之后)。

我认为该wc命令删除尾随换行符(尾随我的意思是在 EOF 处)是否正确,或者我的一段代码不正确?

可能是我增加了一个额外的单位?

这是我的代码:

#include <stdio.h>
#include <string.h>

int checkForNewLine(char* line, int lineSize); 

int main(int argc, char **argv) {
    // declare variables
    FILE *inputFile;                        // pointer to inputted file
    inputFile = fopen(argv[1], "r");        // set input file to 2nd cmd-line arg.
    int newLineCount = 0;
    int newLineIncr = 0;

    // if file is not found
    if (inputFile == NULL){
        printf("%s", "File not found\n");
        return (-1);                        // end program
    }

    char line[201];                         // set line to 200 char MAX. 


    while (fgets(line, 201, inputFile) != NULL){

        // new line count
        newLineCount = newLineCount + checkForNewLine(line, 201); 
    } 
    if (feof(inputFile)) {
    } 
    else {
        printf("%s", "Some Other Error...");
    }

    printf("New Line Count [%d]\n", (newLineCount));

    fclose(inputFile);

}

int checkForNewLine(char *line, int lineSize){
    int count = 0;
    for (int i = 0; i < lineSize; i++) {
        if (line[i] == '\0'){
            count++;
            printf("count amount: %d\n", count);
            break;
        }
    }
    return count;
}
Run Code Online (Sandbox Code Playgroud)

mur*_*uru 5

来自man 3 fgets

The fgets() function shall read bytes from stream into the array
pointed to by s, until n?1 bytes are read, or a <newline> is read and
transferred to s, or an end-of-file condition is encountered.
Run Code Online (Sandbox Code Playgroud)

所以你的代码计算最后一行,不管它的末尾是否有换行符(它没有),因为遇到了 EOF。毕竟,该checkForNewLine()函数正在检查空字符,而不是换行符。使用od,hexdump等来验证输入文件的最后一个字符是什么。