Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C function that counts lines in file

Tags:

c

When I try to run my program, I get the wrong number of lines printed.

LINES: 0

This is the output although I have five lines in my .txt file

Here is my program:

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

int countlines(char *filename);

void main(int argc, char *argv[])
{
  printf("LINES: %d\n",countlines(argv[1]));         
}


int countlines(char *filename)
{
  // count the number of lines in the file called filename                                    
  FILE *fp = fopen(filename,"r");
  int ch=0;
  int lines=0;

  if (fp == NULL);
  return 0;

  lines++;
  while ((ch = fgetc(fp)) != EOF)
    {
      if (ch == '\n')
    lines++;
    }
  fclose(fp);
  return lines;
}

I am sure it is a simple mistake but I am new to programming. Any help would be greatly appreciated.

like image 274
Michael_19 Avatar asked Oct 04 '12 18:10

Michael_19


People also ask

How would you count the lines in a file?

The wc command is used to find the number of lines, characters, words, and bytes of a file. To find the number of lines using wc, we add the -l option. This will give us the total number of lines and the name of the file.

Is there any count function in C?

The count() function is available in the algorithm. h header file in C++. This function is used to get the number of appearances of an element in the specified range.

Can you write a program to count the number of input lines?

Example. #include<iostream> using namespace std; #define FILENAME "test. txt" int main() { FILE *fp; char ch; int linesCount=0; //open file in read more fp=fopen(FILENAME,"r"); if(fp==NULL) { printf("File \"%s\" does not exist!!!


2 Answers

Here is my function

char *fileName = "input-1.txt";
countOfLinesFromFile(fileName);

void countOfLinesFromFile(char *filename){
FILE* myfile = fopen(filename, "r");
int ch, number_of_lines = 0;
do
{
    ch = fgetc(myfile);
    if(ch == '\n')
        number_of_lines++;
}
while (ch != EOF);
if(ch != '\n' && number_of_lines != 0)
    number_of_lines++;
fclose(myfile);
printf("number of lines in  %s   = %d",filename, number_of_lines);

}

like image 200
Samir Avatar answered Sep 29 '22 11:09

Samir


while(!feof(fp))
{
  ch = fgetc(fp);
  if(ch == '\n')
  {
    lines++;
  }
}

But please note: Why is “while ( !feof (file) )” always wrong?.

like image 30
Lundin Avatar answered Sep 29 '22 09:09

Lundin