gpt4 book ai didi

c - strtok segmentation fault,仅当输入文件的第一行为空白时给出段错误

转载 作者:太空狗 更新时间:2023-10-29 12:13:01 35 4
gpt4 key购买 nike

我正在使用 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()

Here is a link to source you might find useful

关于c - strtok segmentation fault,仅当输入文件的第一行为空白时给出段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35318827/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com