我正在使用 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
第一行是空白(我认为只是一个返回字符)和“real 0m1.25s” ' 是第二行。我只想读第二行。当我尝试读取临时变量时发生错误。
有趣的是,我在另一个程序中使用了几乎相同的代码来完成相同的工作,并且它有效。唯一的区别是,在上一个项目的输入文件中没有空行或制表符。所以我很困惑请帮忙。
PS:我使用的是德语键盘,因此它会自行将单词大写,对此感到抱歉。
最佳答案
请使用sscanf()
反而。除非绝对必要,否则应不惜一切代价避免使用 strtok()
。
关于c - strtok段错误,仅在输入文件的第一行为空时给出段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35318827/