1

I want to pass lines of a file using strtok; the values are comma separated. However, strtok also reads blank lines which only contain spaces. Isn't it suppose to return a null pointer in such a situation?

How can I ignore such a line? I tried to check NULL, but as mentioned above it doesn't work.

drox
  • 7,523
  • 4
  • 23
  • 34
  • What is the format of the input file ? – cnicutar Jun 08 '11 at 04:40
  • @cnicutar it is a plain text file with two values in each line separated by a comma. – drox Jun 08 '11 at 04:51
  • 3
    The first call to `strtok` is probably returning the whole line as first token. Why not checking the line contents, after reading it from the file, before splitting it with `strtok`. – pascal Jun 08 '11 at 04:52
  • @pascal i wanted to find out whether there is a way to do it using the strtok itself. But it seems I'll have to go with what you suggested. Wonder why strtok reads the line when the given delimiter does not exist in it. – drox Jun 08 '11 at 04:59
  • 1
    A line "foo" can be understood as a shortcut for "foo,,,,". Without delimiter, the whole line contents is the first item. – pascal Jun 08 '11 at 05:01

1 Answers1

0
void function_name(void)
{

  const char delimiter[] = ",";
  char line_read[9000];
  char keep_me[9000];
  int i = 0;

  while(fgets(line_read, sizeof(line_read), filename) != NULL)
  {
      /*
       * Check if the line read in contains anything
       */
      if(line_read != NULL){
          keep_me[i] = strtok(line_read, delimiter);
          i++;
          }
  }

}

So to explain.

You're reading in your file using a while loop which reads the entire file line by line (fgets) into the array line_read.

Every time it reads in a line it will check to see if it contains anything (the NULL check).

If it does contain something it was parse it using strtok and read it into keep_me otherwise it will stay in the line_read array which you obviously don't use in your program.

samdunne
  • 306
  • 1
  • 2
  • 14
  • 1
    `line_read != NULL` will always be true: `line_read` is an array – pmg Jun 23 '11 at 21:22
  • 2
    There are several issues in this answer, correct me if I'm wrong. (1) is what @pmg mentioned. `line_read` is not a pointer to check for `NULL`. (2) `strtok` returns a `char *`, you assigns it to a memory location which stores a character. (3) calling `strtok` once is not enough to read several values in the line. – drox Jul 07 '11 at 10:22
  • 1
    @Dulanja: you're correct; all the issues you noticed need to be fixed. – pmg Jul 07 '11 at 10:32