awk equivalent code in C for printing NF

Hi all !

whether anyone in forum knows what awk will use while printing number of fields in file(NF) ?

for example

 awk END'{print NF}' file 

prints number of columns in file

if anyone knows equivalent code in C kindly share or explain logic behind it

The source code for the latest release of GNU awk is available from the GNU project's ftp server and its many mirrors.

The current development sources are available through the gawk project on savannah.

Thank you so much Yoda

This prints number of fields for every line and the total last.

awk '{print NF;t+=NF} END {print "total="t}'

Dear Jotne my intention is to know what awk will use internally when you type

awk 'END{print NF}' file

on terminal, in fact I am searching for c code to do the same..

for instance in C we use following to find line count thats NR in awk

// Line Count
        while(1)
            {
            ch=fgetc(fp);
            if(ch==EOF)
                break;
            if(ch=='\n')
                NR++;
            }

This is an occasional misconception in programming languages... awk does not have a "print number of fields in end block" piece of code, that'd be an oddly specific thing to have. You'd have to find two separate, independent things in awk's source code:

1) Whatever sets the NF special variable.
2) Whatever causes the END code block to be run.

There are many ways to do it in C, but you almost certainly wouldn't be doing it the way awk does it, which can be quite complex -- some versions of awk let you use a regex for the field separator...

One way:

char fs=' ';
const char *p="a b c d e";
int nf=0;

// Keep looping until you can't find fs
while(p=strchr(p, fs)) nf++;

printf("nf=%d\n", nf);

thank you..so much dear...I added end block so that it will print only one value rather than printing NF of each line..
once again thank you..for explanation..

Actually, it does not (necessarily). If NF is still defined in the END section - which is not guaranteed in all awk versions - it will print the number of fields in the last line/row of the last file in the input stream. This may be different from No. of cols in other lines / other files!
This comment may seem nit picking, but I made it to prevent misconception of how awk works.

Yes. I agree with you.