c - C 中的行计数但排除空行

标签 c

我有以下程序,但有一个问题。首先是不起作用的程序部分:

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

int main()
{
    FILE *fp;
    FILE *fp2;
    char ch;
    char fnamer[100];
    char fnamer2[100];  //Storing File Path/Name of Image to Display
    printf("\n\nPlease Enter the Full Path of the Image file you want to view: \n");
    scanf("%s",&fnamer);
    fp=fopen(fnamer,"r");
    if(fp==NULL)
    {
        printf("Error!");
        exit(1);
    }
    printf("\n\nPlease Enter the Full Path of the Image file you want to write to: \n");
    scanf("%s",&fnamer2);
    fp2=fopen(fnamer2,"w");
    if(fp2==NULL)
    {
        printf("Error!");
        exit(1);
    }
    else
    {
        // printf("test\n");
    }



    int line_number = 0;
    int charsOnLine = 0;

    fprintf(fp2, "%d: ", ++line_number);  /* put line number in output file */
    printf("%d: ", line_number);


    while((ch = fgetc(fp)) != EOF )
    {
        //printf("test2");
        fputc(ch,fp2);
        printf("%c", ch);
        if ( ch != '\n' && charsOnLine ==0 )
        {
            fprintf(fp2, "%d:", ++line_number );  /* put line number in output file */
            printf("%d: ", line_number);
        }
        //        if (ch != '\n' && charsOnLine 0 ){
        //          fprintf(fp2, "%c", ch);
        //        printf("%d", ch);
        //  }
    }

    fclose;
    fclose(fp);
    // fclose(fp2);
    // getch();
}

程序需要计算行数,给它们一个数字,但跳过空白行。但问题是:当我运行此代码时,它会为所有字符提供一个数字。

最佳答案

您可以使用标志来记住刚刚开始新行的时间。第一次看到不等于 '\n' 的字符时,您将打印行号并清除标志。

类似于:

int line_number = 0;
int newLine = 1;

while((ch = fgetc(fp)) != EOF )
{
    if (ch == '\n')
    {
        newLine = 1;
    }
    else
    {
        if (newLine)
        {
            fprintf(fp2, "%d:", ++line_number );
            printf("%d: ", line_number);
            newLine = 0;
        }
    }
    fputc(ch,fp2);
    printf("%c", ch);
}

关于c - C 中的行计数但排除空行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43064585/

相关文章:

c++ - 字符串文字中的反斜杠字符

c - 如何开发这个算法?

java - 是否有与 unputc 等效的 Java?

c - 如何减去两个 time_t 值(difftime 返回 double 而不是 time_t)?

c - 父进程在挂起时仍然接收信号

c - char和int的指针

c - lab10.c :18:1: error: expected identifier or ‘(’ before ‘{’ token { ^ lab10. c:31:1: 错误: ‘(’ token 之前的预期标识符或 ‘{’

c - execve grep 进程永不退出

c - 我从哪里获得 BIOS.h 文件,以便在 Mingw 中导入?

c - 在 POSIX 中以微秒粒度调度事件