File length calculation does not work

#include "stdio.h"
#include "stdlib.h"
int main()
{
    FILE *fp;
    int noOfLines =0;
    char fname[]="Rtl_Prod_Id.txt";
    printf(fname);
    fp=fopen(fname,"r");
    char ch;

    //looping for every line
    do {
        ch=fgetc(fp);
        if (ch=='\n')
            noOfLines++;
    } while(ch!=EOF);

    //line before the last line
    if (ch!='\n'&&noOfLines!=0)
        noOfLines++;
    fclose(fp);
    printf("%d",noOfLines);
    return 0;
}

I'm just trying to calculate the number of lines in my file. The same does not return me any result.

What are the possible mistakes that I make

Environment: AIX and compiler: CC

thank

Edit: my program compiles successfully, but nothing appears at runtime of the .Out file

PS: Although I got a response. thanks https://stackoverflow.com/users/434551/r-sahu . I changed char ch; on int ch; . but I wonder why? What's wrong with the char declaration ?, How am I going to check the "\ n" and EOF characters, why the whole afterwards?

+4
source share
4 answers

This is a wild shot, but a line change

char ch;

to

int ch;

. fgetc int, char.

+1

, char AIX unsigned char.

fgetc() int, -1 () EOF. , unsigned char (EOF 255), ch != EOF , .

int ch; ; btw, , -Wall ( ).

+4
  • <...> "..." , stdio.h stdlib.h.

  • fopen .

  • fgetc() int, char.

  • . do {} while ch EOF, '\n'. , , - '\n' do {} while.

, :

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

int main(int argc, char *argv[])
{
    FILE *fp;
    int noOfLines, isRem, ch;

    if (argc > 1) {
        fp = fopen(argv[1],"r");
        if (fp == NULL) {
            perror("fopen");
            exit(EXIT_FAILURE);
        }
    }
    else {
        fp = stdin;
    }

    noOfLines = 0;
    isRem = 0;

    //looping for every line
    do {
        ch = fgetc(fp);
        if (ch != EOF)
            isRem = 1;
        if (ch == '\n') {
            noOfLines++;
            isRem = 0;
        }
    } while (ch != EOF);

    //line before the last line
    if (isRem)
        noOfLines++;

    if (argc > 1)
        fclose(fp);

    printf("%d\n", noOfLines);

    exit(EXIT_SUCCESS);
}

:

$ wc -l t000.c 
44 t000.c
$ ./a.out t000.c 
44
$ echo -e "abc\ndef" | ./a.out 
2
$ echo -ne "abc\ndef" | ./a.out 
2
+1

char ch; int ch;, , ? char ?, '\n' EOF ?

EOF -1 INT, ch INT.

, getchar()

int getchar(void);

getchar() .

There is some confusion about EOF, more about that here

0
source

Source: https://habr.com/ru/post/1537457/


All Articles