Counting the words in a file


 
Thread Tools Search this Thread
Top Forums Programming Counting the words in a file
# 1  
Old 06-12-2010
Hammer & Screwdriver Counting the words in a file

Please find the below program. It contains the purpose of the program itself.
Code:
/* Program : Write a program to count the number of words in a given text file */
/* Date : 12-June-2010 */

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

int main( int argc, char *argv[] )
{
	FILE *fp;
	char word[100];
	int lp_cnt=0,w_cnt=0;

	if ( argc!=2 ) {
		printf("Usage Wrong\n");
		exit(1);
	}

	if ((fp=fopen(argv[1],"r")) == NULL) {
		printf("File opening error\n");
		exit(1);
	}

	while ( !feof(fp) ) {
		fgets(word,100,fp);
		word[strlen(word)]='\0';
		while(word[lp_cnt]!='\0') {
			if ( (word[lp_cnt]!=' ' && word[lp_cnt+1]==' ') || (word[lp_cnt]!='\n' && word[lp_cnt]!=' ' && word[lp_cnt+1]=='\n')) {
					++w_cnt;
				}
			++lp_cnt;
		}
	}
	printf("word count is %d\n",w_cnt);
	return 0;
}

On execution of the program with the file ga_hey containing the content:
I LOVE YOU
It gives the correct word count as 3
Code:
ganesh@ubuntu:~/my_programs/c/letusc/chap11$ cat ga_hey
I LOVE YOU
ganesh@ubuntu:~/my_programs/c/letusc/chap11$ ./ga ga_hey
word count is 3

However if I execute the same program with the 2 line content its not working. Please see below:
Code:
ganesh@ubuntu:~/my_programs/c/letusc/chap11$ cat ga_you
I LOVE YOU
HOW ARE YOU
ganesh@ubuntu:~/my_programs/c/letusc/chap11$ ./ga ga_you
word count is 3

I don't know where I am going wrong in the above program. Somewhere near fgets I think. Can you please help me on this.

---------- Post updated at 08:21 PM ---------- Previous update was at 04:02 PM ----------

I corrected it myself with the below changes in my program:


Code:
/* Program : Write a program to count the number of words in a given text file */
/* Date : 12-June-2010 */

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

int main( int argc, char *argv[] )
{
	FILE *fp;
	char word[100];
	int lp_cnt=0,w_cnt=0;

	if ( argc!=2 ) {
		printf("Usage Wrong\n");
		exit(1);
	}

	if ((fp=fopen(argv[1],"r")) == NULL) {
		printf("File opening error\n");
		exit(1);
	}

	while ( !feof(fp) ) {
		while(fgets(word,100,fp)!=NULL) {
			lp_cnt=0;
			while(word[lp_cnt]!='\0') {
				if ( (word[lp_cnt]!=' ' && word[lp_cnt+1]==' ') || (word[lp_cnt]!='\n' && word[lp_cnt]!=' ' && word[lp_cnt+1]=='\n')) {
						++w_cnt;
				}
				++lp_cnt;
			}
		}
	}
	printf("word count is %d\n",w_cnt);
	return 0;
}


Now the expected output is coming..

Thanks,
Ramkrix

Moderator's Comments:
Mod Comment Setting the style to a monospaced font isn't the same as [CODE] tags

Last edited by pludi; 06-12-2010 at 12:48 PM.. Reason: Please use code tags
This User Gave Thanks to ramkrix For This Post:
# 2  
Old 06-12-2010
Hello,

use wc.

Code:
wc -w file

Quote:
Why Re-Invent Wheels?
Regards,
Gaurav.
# 3  
Old 06-14-2010
One more way would be

Code:
int main( int argc, char *argv[] )
{
    FILE *fp;
    char word[100];
    int lp_cnt=0,w_cnt=0;
 
    if ( argc!=2 ) {
        printf("Usage Wrong\n");
        exit(1);
    }
 
    if ((fp=fopen(argv[1],"r")) == NULL) {
        printf("File opening error\n");
        exit(1);
    }
 
    while ( !feof(fp) ) {
fscanf(fp,"%s",word);
w_cnt++;
}
printf("word count is %d\n",w_cnt);
    return 0;
}


Last edited by Scott; 06-14-2010 at 09:43 AM.. Reason: Please use code tags
# 4  
Old 06-14-2010
showkat161,
in a file with 10 words (5 in 1st line, 5 in 2nd line) your code printed 11.
in a file with 18 words (5 in 1st line, 5 in 2nd line, 8 in the 3rd line) your code printed 19.
# 5  
Old 06-15-2010
This looks Odd

Can you try pressing delete at the end of the file, so that the cursor does not move further( I mean delete all blank lines)... Please let me know if it resolves the issue.

---------- Post updated at 10:52 AM ---------- Previous update was at 08:32 AM ----------

I guess I got the answer to the bug that you pointed out.. Please see the link below...
Cprogramming.com FAQ > Why it's bad to use feof() to control a loop

based on this my previous program needs a modification
Code:
int main( int argc, char *argv[] )
{
    FILE *fp;
    char word[100];
    int lp_cnt=0,w_cnt=0;
 
    if ( argc!=2 ) {
        printf("Usage Wrong\n");
        exit(1);
    }
 
    if ((fp=fopen(argv[1],"r")) == NULL) {
        printf("File opening error\n");
        exit(1);
    }
 
    while ( (fscanf(fp,"%s",word))==1 ) {
       w_cnt++;
    }
printf("word count is %d\n",w_cnt);
    return 0;
}

I tested this program on Solaris and Ubuntu it worked fine on both

HTH
Showkat

Last edited by Scott; 06-15-2010 at 06:36 PM.. Reason: Code tags, please...
# 6  
Old 06-15-2010
Quote:
Originally Posted by gaurav1086
Hello,

use wc.

Code:
wc -w file



Regards,
Gaurav.

I don't think that is the intent of the question. How else can one learn by practice to see how commands are implemented and what is the difficult with them? Smilie
# 7  
Old 06-15-2010
showkat161, works now Smilie
Login or Register to Ask a Question

Previous Thread | Next Thread

10 More Discussions You Might Find Interesting

1. Shell Programming and Scripting

Counting specific words from the log

Hi, I need a shell script which can provide details from error logs like this Aug 23 21:19:41 red mountd: authenticated mount request from bl0110.bang.m pc.local:651 for /disk1/jobs (/disk1) Aug 23 08:49:52 red dhcpd: DHCPDISCOVER from 00:25:90:2b:cd:7c via eth0: unknown client Aug 24... (2 Replies)
Discussion started by: ratheeshp
2 Replies

2. Shell Programming and Scripting

Counting occurrence of all words in a file

Hi, Given below is the input file: http://i53.tinypic.com/2vmvzb8.png Given below is what the output file should look like: http://i53.tinypic.com/1e6lfq.png I know how to count the occurrence of 1 word from a file, but not all of them. Can someone help please? An explanation on the... (1 Reply)
Discussion started by: r4v3n
1 Replies

3. Shell Programming and Scripting

counting words with perl?

how to use perl to count number of lines, words characters in a file. (3 Replies)
Discussion started by: winter9
3 Replies

4. Shell Programming and Scripting

Counting words from one file in another file

Hi All, I have written a script on this but it does not do the requisite job. My requirement is this: 1. I have two kinds of files each with different extensions. One set of files are *.dat (6000 unique DAT files all in one directory) and another set *.dic files (6000 unique DIC files in all... (5 Replies)
Discussion started by: shoaibjameel123
5 Replies

5. Shell Programming and Scripting

Counting number of files that contain words stored in another file

Hi All, I have written a script on this but it does not do the requisite job. My requirement is this: 1. I have two kinds of files each with different extensions. One set of files are *.dat (6000 unique DAT files all in one directory) and another set *.dic files (6000 unique DIC files in... (1 Reply)
Discussion started by: shoaibjameel123
1 Replies

6. Shell Programming and Scripting

Help in counting the no of repeated words with count in a file

Hi Pls help in solving my doubt.Iam having file like below file1.txt priya jenny jenny priya raj radhika priya bharti bharti Output required: I need a output like count of repeated words with name for ex: priya 3 jenny 2 (4 Replies)
Discussion started by: bha148
4 Replies

7. Shell Programming and Scripting

Counting words

Hi Is there a way to count the no. of words in all files in directory. All are text files.I use wc -w but somehow i am not getting the rite answer. Is there an alternative. Thanks in advance (9 Replies)
Discussion started by: kinny
9 Replies

8. UNIX for Dummies Questions & Answers

counting words

if i have a long list of data, with every line beginning with an ip-address, like this: 62.165.8.187 - - "GET /bestandnaam.html HTTP/1.1" 200 5848 "http://www.domeinnaam.nl/bestandnaam.html" "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)" how do i count which ip-adresses are mentioned... (3 Replies)
Discussion started by: FOBoy
3 Replies

9. UNIX for Dummies Questions & Answers

counting words then amending to a file

i want to count the number of words in a file and then redirect this to a file echo 'total number of words=' wc -users>file THis isnt working, anyone any ideas. (1 Reply)
Discussion started by: iago
1 Replies

10. Shell Programming and Scripting

Counting words in a file

I'm trying to figure out a way to count the number of words in the follwing file: cal 2002 > file1 Is there anyway to do this without using wc but instead using the cut command? (1 Reply)
Discussion started by: r0mulus
1 Replies
Login or Register to Ask a Question