![]() |
word count
how to find and print only the first word from each line of a file using C
|
Good Lord, C is totally wrong choice for that.
Solution in 6 other languages: awk: Code:
awk '{print $1}' foo.txtCode:
sed 's/^\([^ ]*\).*$/\1/' foo.txtCode:
perl -pe '($_) = split(" ", $_); $_=~s/$/\n/' foo.txtCode:
perl -pe '$_=~ s/^(\w+).*$/$1/;' foo.txtCode:
while {[ gets stdin line] >= 0} { puts [lindex [split $line " "] 0] }Code:
cut -f1 -d' ' foo.txtCode:
python -c $'import sys;\ndef fword(x): print x.split(" ")[0].strip();\nmap(fword,sys.stdin.readlines());' < foo.txt |
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 12:52 AM. |