Results 1 to 3 of 3
  1. #1
    Join Date
    Jun 2004

    Unanswered: read a line from file and search using C


    I have a file called "test" that has several lines, such as:


    I need to read line by line and split the line by the ",".

    How do I read the line and split it?


  2. #2
    Join Date
    Nov 2006
    Brighton, UK

    Talking Switch to Delphi

    Man, I guess you haven't got too much programming experience sofar, so why not try switching to Delphi? Delphi is GREAT! And I could give you answers to questions like this every now and then. I don't know C... I never really cared for it...

  3. #3
    Join Date
    Aug 2006
    The Netherlands
    Are you shure you want to do this in C? Things like this can be done much easier in more dedicated languages like AWK or PERL. If I would do this in AWK, on the UNIX prompt, for instance I would do it like:
    awk -F "," '{
    	        for(i =1; i <= NF; i++)
    		     printf("%s ", $i)
                }' test
    The syntax is very similar to C but what happens here implicitly is that a filepointer to "test" is opened, the file is read line by line, with the '-F' flag the fieldseparator is set to ',' (instead of the default space/tab) and the builtin fieldcount variable 'NF' is set to the number of fields. With this you only need to code what has to be done with the fields inside the actionpart, between { and }, that performs on every inputline. In this case the fields of the line <$i> are printed as strings separated by spaces <printf("%s "> and concluded with the newline character for every line.

    In C you have to take care of all of these things yourself with declaring a filepointer <FILE *ifp>, opening the filepointer <ifp = fopen("test", "r");>, read the inputline <probably with 'fscanf(ifp, "%s,%s,%s", &fld1, &fld2, &fld3);'>, define what you want to do with the fields and close the filepointer <fclose(ifp)>.

    AWK comes automatically with every UNIX/Linux distribution and is available for Windows as freeware.

    If you don't work with UNIX and don't want to go through all the fuzz with installing AWK consider PERL as the easiest alternative. Works similar as AWK in this case but needs a little more code and is available for UNIX as well as Windows. Besides, unlike AWK PERL can perform most of the common tasks you can do with C.

    And if you insist in doing it with C buy a good explainatory book...


Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts