在我的节目中,我正在用strtok削减我的char *。当我在Windows上检查时它会像我想要的那样切割,但是当我在Linux上做同样的事情时,它做错了。
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;
}
答案 0 :(得分:1)
我在代码中找不到任何错误但我强烈建议使用strtok_r()而不是strtok()。我觉得strtok应该过时,在MT环境下不安全。 另外我认为strtok_r将帮助您轻松找到错误,因为它有另一个参数来跟踪解析进度,因此很容易找到错误: http://www.mkssoftware.com/docs/man3/strtok_r.3.asp
答案 1 :(得分:1)
我在C中面临同样的问题。我的代码在Windows上完美运行,但我在Linux中使用strtok()
时遇到错误。我只是忘了包含string.h
:
#include <string.h>