Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

352
Vistas
strtok segmentation fault, just gives a segmentation fault when the first line of input file is blank

I am using AIX. There are several posts of Segmentation fault with strtok but I could not find any to help me.

I am writing a c program and I want to read a file in the program and then sort this line (I just need the minutes and the seconds at the end of the second line).

here is a snippet from my code:

   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++;

        }
}

The file I am trying to read is has this inside:

real    0m1.25s
user    0m0.09s
sys 0m0.02s

The first line is blank (only a return character I think) and 'real 0m1.25s ' is the second line. I want to read only the second line. The error occurs when I try to read the temp variable.

The funny thing is I have used nearly the same code for the same job in another program and it worked. The only difference was that in the input file of the previous project there were no blank lines or tabs. So I am confused please help.

PS: I am using a German keyboard so it capitalizes words on its own, sorry about that.

over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

Please use sscanf() instead. Try to avoid strtok() at all costs unless otherwise absolutely neccessary.

Here is a link to source you might find useful

over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda