如何计算C中文件的空行?

时间:2014-01-21 17:34:29

标签: c

所以我要做的就是计算空行,这意味着不仅仅包含' \ n'还包括空格和制表符号。任何帮助表示赞赏! :)

char line[300];
int emptyline = 0;
FILE *fp;
fp = fopen("test.txt", "r");
if(fp == NULL)
{
    perror("Error while opening the file. \n");
    system("pause");
}
else
{
    while (fgets(line, sizeof line, fp)) 
    {
        int i = 0;
        if (line[i] != '\n' && line[i] != '\t' && line[i] != ' ') 
        {
           i++;
        }
        emptyline++;
    }
    printf("\n The number of empty lines is: %d\n", emptyline);
}
fclose(fp);

4 个答案:

答案 0 :(得分:1)

您应该尝试在SO上发布时正确使用您的代码。您正在递增iemptyline,但在el的通话中使用printf()。然后,我不知道代码中应该包含}ine的内容。请至少付出努力。

首先,您为每行增加emptyline,因为它超出了if声明。

其次,您需要测试整行,看它是否包含任何不是空白字符的字符。只有在情况属实的情况下才应增加emptyline

int IsEmptyLine(char *line)
{
    while (*line)
    {
        if (!isspace(*line++))
            return 0;
    }
    return 1;
}

答案 1 :(得分:0)

您在每次迭代时都会递增emptyline,因此您应将其包装在else块中。

答案 2 :(得分:0)

在进入行循环之前,递增emptyLine计数器,如果非空白字符被加密,则递减emptyLine计数器然后打破循环。

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

int getEmptyLines(const char *fileName)
{
    char line[300];
    int emptyLine = 0;
    FILE *fp = fopen("text.txt", "r");
    if (fp == NULL) {
        printf("Error: Could not open specified file!\n");
        return -1;
    }
    else {
        while(fgets(line, 300, fp)) {
            int i = 0;
            int len = strlen(line);
            emptyLine++;
            for (i = 0; i < len; i++) {
                if (line[i] != '\n' && line[i] != '\t' && line[i] != ' ') {
                    emptyLine--;
                    break;
                }
            }
        }
        return emptyLine;
    }
}

int main(void)
{
    const char fileName[] = "text.txt";
    int emptyLines = getEmptyLines(fileName);
    if (emptyLines >= 0) {
        printf("The number of empty lines is %d", emptyLines);
    }
    return 0;
}

答案 3 :(得分:0)

让我们从逻辑上思考这个问题,让我们使用函数来清楚地说明发生了什么。

首先,我们要检测仅由空格组成的行。所以让我们创建一个函数来做到这一点。

bool StringIsOnlyWhitespace(const char * line) {
    int i;
    for (i=0; line[i] != '\0'; ++i)
        if (!isspace(line[i]))
            return false;
    return true;
}

现在我们有了一个测试函数,让我们围绕它构建一个循环。

while (fgets(line, sizeof line, fp)) {
    if (StringIsOnlyWhitespace(line))
        emptyline++;
}

printf("\n The number of empty lines is: %d\n", emptyline);

请注意,fgets()不会在至少包含sizeof(line)个字符的行上返回完整行(只是其一部分)。