954,499 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Getting wrong line from a file

This program should extract the first line.

Somehow I'm getting the last line instead of the first...

This is the textfile:
N100 G96 S200
N115 G0 X600 Z-1004.95 T11 D2 M3 M7 H10
N125 G0 X500
N130 G1 X419 F0.5
N135 G1 Z-1004
N140 G0 X500
N145 G0 Z-419.7
N150 G0 X405

Trying to get the first line and place it in a character array with this .c program :

#include <stdio.h>
#include <stdlib.h>

int main (int argc, char *argv[])
{
  FILE *filePtr;
  int i = 0;
  char line[255];
  
  if ((filePtr=fopen(argv[1], "r")) == NULL)
  { 
    printf("Cannot open file.\n");
    return -1;
  }
  
    // get the first line
    while ( line[i] != '\0' ) {
      fgets(line, sizeof(line), filePtr);
      ++i;
    }
    
    // print it
    printf("Code: %s", line);
  // close the file at hand
  fclose (filePtr); 
  
  return 0;
}


Output: Code: N150 G0 X405

Why am I getting the last line starting with N150 instead of the N100 line?

Thanks in advance.

DJWK
Newbie Poster
13 posts since Oct 2009
Reputation Points: 10
Solved Threads: 0
 

Okey, i'm too tired for this... remove the loop and it works.

Time to get some sleep :)

DJWK
Newbie Poster
13 posts since Oct 2009
Reputation Points: 10
Solved Threads: 0
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: