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 fi
You're opening a file, then passing the file pointer to a function that only wants a file name to open the file itself. You can simplify your call to;
void main(void)
{
printf("LINES: %d\n",countlines("Test.txt"));
}
EDIT: You're changing the question around so it's very hard to answer; at first you got your change to main()
wrong, you forgot that the first parameter is argc, so it crashed. Now you have the problem of;
if (fp == NULL); // <-- note the extra semicolon that is the only thing
// that runs conditionally on the if
return 0; // Always runs and returns 0
which will always return 0. Remove that extra semicolon, and you should get a reasonable count.
Here is complete implementation in C/C++
#include <stdio.h>
void lineCount(int argc,char **argv){
if(argc < 2){
fprintf(stderr,"File required");
return;
}
FILE *fp = fopen(argv[1],"r");
if(!fp){
fprintf(stderr,"Error in opening file");
return ;
}
int count = 1; //if a file open ,be it empty, it has atleast a newline char
char temp;
while(fscanf(fp,"%c",&temp) != -1){
if(temp == 10) count++;
}
fprintf(stdout,"File has %d lines\n",count);
}
int main(int argc,char **argv){
lineCount(argc,argv);
return 0;
}
https://github.com/KotoJallow/Line-Count/blob/master/lineCount.c
You have a ; at the end of the if
.
Change:
if (fp == NULL);
return 0;
to
if (fp == NULL)
return 0;
while(!feof(fp))
{
ch = fgetc(fp);
if(ch == '\n')
{
lines++;
}
}
But please note: Why is “while ( !feof (file) )” always wrong?.
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);
}
You declare
int countlines(char *filename)
to take a char *
argument.
You call it like this
countlines(fp)
passing in a FILE *.
That is why you get that compile error.
You probably should change that second line to
countlines("Test.txt")
since you open the file in countlines
Your current code is attempting to open the file in two different places.