views:

104

answers:

3

I'm novice so be gentle.

trying to read a file of strings as such: "1,Duck_Soup,1933,Comedy,5,12" and tokenize it to different vars for each of the tokens between the commas.

That's my code and I keep getting "segmentation fault" no matter what I try. Please help me fix the code, thank you. For starters I want to make it print the token separately, at least so I'll know it's working.

#include <stdio.h>

int main(int argc, char* argv[]) {
  int i;
  FILE *fd;
  char fileName[40];
  char line[100];
  char  *pch;

  strcpy(fileName,argv[1]);

  if((fd = fopen(fileName, "r")) == NULL) {
   printf("Error opening file. \n");
   return -1;
  }

  while( fgets(line, sizeof(line), fd) != NULL) {
    pch = strtok (line, ",");
    while (pch != NULL ) {
      printf("%s", pch); 
      pch = strtok (NULL, ",");
    }

  }

 fclose(fd); 
} 
A: 

Too small fileName buffer probably. You don't need it at all, just pass argv[1] to fopen.

adf88
A: 

It works fine for me. Make sure you are passing the name of the input file on the command line.

Your program does not check if the user has provided the input file on command line or not. You should add this check.

codaddict
I will add the check thank you.I still don't get how it works for you.I only get segmentation fault.I am passing the correct name..Any idea?
Gal
A: 

Ok, thank you very much. The problem was that I forgot to include string.h! silly me.

Gal
Its interesting how including string.h gets rid of the segfault.
codaddict
@codaddict, for a function that is not known, the compiler assumes a return value of `int` and a ... signature. No wonder if for `strtok` this gets something wrong on the way. The best to avoid such a thing is to always compile with all warnings on. Any decent compiler will tell you that there is a problem.
Jens Gustedt
@Gal - For future reference, you can post your response to an answer as a comment, not another answer. :)
apollodude217