LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   word count in a line (https://www.linuxquestions.org/questions/programming-9/word-count-in-a-line-222020/)

pantera 08-24-2004 09:37 PM

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

Dark_Helmet 08-24-2004 09:50 PM

If you separate words by using only spaces (not tabs, not punctuation, and not any other characters), you could do this:

sed "s/^[ ]*\([^ ]\+\).*/\1/" some_file

chrism01 08-25-2004 05:26 AM

This may be a homework qn (cf: http://www.catb.org/~esr/faqs/smart-....html#homework) ...
However, as hinted by Dark_Helmet, the 1st step is to determine the separator char(s) between words and go from there....
There are several ways of doing this, but personally I'd prob consider the strtok() fn.... depending on the answer to the 1st step qn.

jim mcnamara 08-25-2004 10:49 AM

Code:

#include <stdio.h>
/* no error checking at all; assumes no leading spaces */         
/* since it's homework - you add error checking */   
/* file =mycode.c */

int main(int argc, char *argv[]){
    char tmp[512]={0x0};
    FILE *in=fopen(argv[1],"r");
    while(fgets(tmp,sizeof(tmp), in)!=NULL){
        for(int i=0;tmp[i]!=' ';i++) printf("%c",tmp[i]);
        printf("\n");
    }
    fclose(in);
    return 0;
}

usage: mycode /path/to/file

Dark_Helmet 08-25-2004 01:14 PM

Hehehe... edited after my response to clarify writing it in C.

It's left as an exercise for the reader to execute shell commands within their program (man popen is a good start). ;)

Who knows, it might get a few "creativity points", then again...


All times are GMT -5. The time now is 02:41 PM.