Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

356
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!