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

标签 c linux segmentation-fault aix

我正在使用 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段错误,仅在输入文件的第一行为空时给出段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35318827/

相关文章:

c - 为另一个架构重建 Linux 内核模块

c - 串行编程 : Sender and Receiver

linux - 如何在 Linux 上开发 OpenGL ES (GLES) 2.0 应用程序?

Php 错误 : failed to open stream: Permission denied in CentOS 7. 1.1503(核心)

c++ - pthread_join 期间的段错误

c - MPI 结构错误

c - 通常在 vim/标签组织中一次使用多个标签文件

c - 如何知道我的程序在运行时实际使用的是哪个共享库?

Python PyEnchant 段错误或无效指针

c++ - 递归 Floodfill 段错误