Hello, I need help with program that counts overall number of lines in file and the empty lines. I have problem with the part with counting. If anyone can help it will be great
Thank you!
Printable View
Hello, I need help with program that counts overall number of lines in file and the empty lines. I have problem with the part with counting. If anyone can help it will be great
Thank you!
What have you tried?
This but it only counts the empty linesCode:char buf[5000], *el, ch;
int counter = 0, nel = 0;
while( !feof(fp) ){
fgets(buf, 5000, fp);
el=buf;
while(*el==' ' || *el=='\t') el++;
if(*el=='\r') el++;
if(*el=='\n') counter++;
}
Dont use feof. It might be causing the problem.
ok guys I made some short code for counting the overall lines
Now I need to make it count the empty lines too. I dont like my old piece of code that uses arrays. Can you help me with that?Code:void countlines(char *fail4e){
int c, el=0, nel=0;
while(!feof(fp)){
c=fgetc(fp);
if(c=='\n') el++;
}
printf("%d", el);
system("pause");
}
You're over-thinking the problem. It's really quite simple. fgets() returns NULL when it reaches an error or END OF FILE.
so a simple
is all you need *IF* you're sure that the size of your buff[] will ALWAYS be larger than any single line of text, in the file.Code:while((fgets(blahblahblah)) != NULL) {
counter++;
}
Which it is.
Just get rid of all the other stuff, and you should be good to go. And don't count on feof any more - it's quite unreliable. Thankfully, it's also unnecessary.
i still need to count the empty(may contain spaces and tabs) and non empty lines :)
You'll need 2 states; empty and non_empty. After a \n reset the state to empty, when reaching the first character thats not a \t or blank, set the state variable to non_empty, and check the state after a newline. If empty, increment it.
Well I know I need to read symbol by symbol and if I meet symb!='\t' || symb!=' ' I need to go to the next line and check it too. But I have no idea how this will look inco C code
Something like that should suffice.Code:while character read is not EOF
if char is newline
line++
lastchar = char
if lastchar != newline
line++
Quzah.
Ok, I understand what you meant by "count the lines and empty lines".
I took that to mean "I have to count all the lines, empty or not", which my code will do. What you meant was "I have to count AND report" the total empty and non empty number of lines.
Here is an old thread on the topic that I'd found interesting (especially page 2):
http://cboard.cprogramming.com/c-pro...-counting.html
thank you all for the replies :)