LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (http://www.linuxquestions.org/questions/programming-9/)
-   -   word count (http://www.linuxquestions.org/questions/programming-9/word-count-224728/)

pantera 08-31-2004 06:03 AM

word count
 
how to find and print only the first word from each line of a file using C

ToniT 08-31-2004 07:14 AM

Good Lord, C is totally wrong choice for that.

Solution in 6 other languages:
awk:
Code:

awk '{print $1}' foo.txt
sed:
Code:

sed 's/^\([^ ]*\).*$/\1/' foo.txt
perl:
Code:

perl -pe '($_) = split(" ", $_);  $_=~s/$/\n/' foo.txt
or other perl implementation:
Code:

perl -pe '$_=~ s/^(\w+).*$/$1/;' foo.txt
tcl: (inside tclsh)
Code:

while {[ gets stdin line] >= 0} { puts [lindex [split $line " "] 0] }
shell script/coreutils:
Code:

cut -f1 -d' ' foo.txt
python:
Code:

python -c $'import sys;\ndef fword(x): print x.split(" ")[0].strip();\nmap(fword,sys.stdin.readlines());' < foo.txt
Do you still want to do that in C?

cppkid 08-31-2004 07:23 AM

Open a file
then get a line in buffer using getline()------------------> see " man getline " for details.
then use strchar() to locate a space character --------------> see " man strchar()"
This will give you the index of first space charecter in that buffer.
strncpy ( first_word , buffer , index_of_space);
printf (first_word)
And then read the next line until the end of file. The code will be something like.

while( feof ( fileptr ) )
{
getline ( buffer, length , fileptr);
strncpy ( first_word , buffer , strchar( *buffer , " " ) );
printf (first_word);
}

There may be more efficient way to do that.


All times are GMT -5. The time now is 03:31 AM.