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.
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.
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.
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!!!
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);
}
while(!feof(fp))
{
ch = fgetc(fp);
if(ch == '\n')
{
lines++;
}
}
But please note: Why is “while ( !feof (file) )” always wrong?.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With