strtok segmentation fault,仅当输入文件的第一行为空白时给出分段错误
strtok segmentation fault, just gives a segmentation fault when the first line of input file is blank
我正在使用 AIX。有几个关于 strtok 的分段错误的帖子,但我找不到任何帮助我的帖子。
我正在写一个c程序,我想在程序中读取一个文件,然后对这一行进行排序(我只需要第二行末尾的分秒)。
这是我的代码片段:
FILE *timeFile;
int x, timeElapsed;
char line[1000], *temp;
int main()
{
x = 0;
timeFile= fopen("time.txt", "r");
if(timeFile==NULL)
{
printf("\nerror opening file time.txt\n");
printf("\nPlease update system time manually\n");
return 1;//error
}
while( x<10 && fgets(line, sizeof(line), timeFile)!= NULL)
{
if( x==1 )//we need data from the second line
{
temp = strtok(line, " ");
printf("\nline: %s",line);//the Output here is as expected 'line: real'
printf("\ntemp: %s",temp);//the error occurs here at temp
break;
}
x++;
}
}
我要读取的文件里面有这个:
real 0m1.25s
user 0m0.09s
sys 0m0.02s
第一行是空白(我认为只有一个return字符)和'real 0m1.25s
' 是第二行。我只想读第二行。当我尝试读取临时变量时发生错误。
有趣的是,我在另一个程序中对相同的工作使用了几乎相同的代码,而且它起作用了。唯一的区别是在之前项目的输入文件中没有空行或制表符。所以我很困惑请帮忙。
PS: 我使用的是德语键盘,所以它会自己将单词大写,对此感到抱歉。
请改用sscanf()
。除非绝对必要,否则尽量避免 strtok()
。
我正在使用 AIX。有几个关于 strtok 的分段错误的帖子,但我找不到任何帮助我的帖子。
我正在写一个c程序,我想在程序中读取一个文件,然后对这一行进行排序(我只需要第二行末尾的分秒)。
这是我的代码片段:
FILE *timeFile;
int x, timeElapsed;
char line[1000], *temp;
int main()
{
x = 0;
timeFile= fopen("time.txt", "r");
if(timeFile==NULL)
{
printf("\nerror opening file time.txt\n");
printf("\nPlease update system time manually\n");
return 1;//error
}
while( x<10 && fgets(line, sizeof(line), timeFile)!= NULL)
{
if( x==1 )//we need data from the second line
{
temp = strtok(line, " ");
printf("\nline: %s",line);//the Output here is as expected 'line: real'
printf("\ntemp: %s",temp);//the error occurs here at temp
break;
}
x++;
}
}
我要读取的文件里面有这个:
real 0m1.25s
user 0m0.09s
sys 0m0.02s
第一行是空白(我认为只有一个return字符)和'real 0m1.25s ' 是第二行。我只想读第二行。当我尝试读取临时变量时发生错误。
有趣的是,我在另一个程序中对相同的工作使用了几乎相同的代码,而且它起作用了。唯一的区别是在之前项目的输入文件中没有空行或制表符。所以我很困惑请帮忙。
PS: 我使用的是德语键盘,所以它会自己将单词大写,对此感到抱歉。
请改用sscanf()
。除非绝对必要,否则尽量避免 strtok()
。