views:

162

answers:

1

In my program I'm cutting my char* with strtok. When I'm checking on Windows it's cut like I want, but when I'm doing the same thing on Linux, it's doing it wrong.

Example :

Windows:

  • my char* (line) is : "1,21-344-32,blabla"
  • in the first time I do strtok I get "1"
  • in the second time I get "21-344-32"

Linux:

  • my char* (line) is : "1,21-344-32,blabla"
  • in the first time I do strtok I get "1"
  • in the second time I get "2"

Code

Result FileReader::InitRead (Manager* mngr, char* pfileName, ofstream &ResultFile)//add /*Manager* mng,*/ + use for: vehicle init
{
     FILE *pfile;
     char fileName[50],line[2000], *word= NULL,*str1=NULL,*str2=NULL,*str3=NULL, *str4=NULL, *str5=NULL, *str6=NULL;
     int wcount=0,lcount=0;
     Vehicle::Vehicle_Type vecEnm = Vehicle::InvalidCarEm;
     bool stop = false;
     string check;

     strcpy(fileName,pfileName);

     if((pfile = fopen(fileName, "r")) == NULL) 
     {
         ResultFile<<"Error Opening vehicles init file, May not exist.\n";
         return Fail;
     }
     else
     { 
      while( fgets(line, sizeof(line), pfile) != NULL ) 
      {
       lcount++;
       wcount=0;
       check.assign(line);
       if(check.size()!=0){
       word = strtok (line,",");
       if ((word[0] != '#') &&  (word[0] != '\r') && (strcmp(line,"\n") != 0))
       {
           wcount++;
           str1 = word;
           vecEnm = (Vehicle::Vehicle_Type)(atoi(str1));
           while ((word != NULL) &&  (wcount < 7) && (!stop))
           {
                 wcount ++;
                 word = strtok (NULL, ",");

                 switch (wcount)
                 {
                        case 2: str2 = word;
                              break;
                        case 3: str3 = word;
                              break;
                        case 4: str4 = word;
                              break;
                        case 5: str5 = word;
                              if ((vecEnm < Vehicle::PlaneEm) || (vecEnm == Vehicle::InvalidCarEm))
                                    stop=true;
                              break;
                        case 6: str6 = word;
                              break;
                        default:break;
                 }
            }

            mngr->TranslateVecInit(vecEnm,str2,str3,str4,str5,str6,ResultFile);

           }//while - line not finished
       }
       str1=str2=str3=str4=str5=str6=NULL;
       stop=false;

       }//reads next line
       fclose(pfile); 
       }
 return Success;
}
+1  A: 

I could not spot anything wrong in your code but I strongly recommend using strtok_r() instead of strtok(). I feel strtok should be made obsolete, its not safe in MT environment. Also I think strtok_r will help you finding the bug easily as it has another parameter to track the parsing progress so its easy to find whats wrong : http://www.mkssoftware.com/docs/man3/strtok_r.3.asp

harry