0

instead of using while loops.

or instead of doing the following to get the 3rd line from a file.

is there a better way ?

perhaps with fseek ? if so how.

FILE *fp;
fp = fopen(path, "r");

char line_one[100];
char line_two[100];
char line_three[100];

fgets(line_one, sizeof line_one, fp);
fgets(line_two, sizeof line_two, fp);
fgets(line_three, sizeof line_three, fp);
fclose(fp);

line_three[strcspn(line_three, "\n")] = 0;
  • Well, I would probably use a function that, when passed an fd, char array pointer and line number, filled the array or returned an error number. fseek() is not really much use unless it's guaranteed that every line is the same length:( – ThingyWotsit Jul 08 '17 at 11:50

1 Answers1

-1

try

fseek(fb,200,SEEK_SET);
fread(buffer,sizeof(char),100,fb)

where buffer an array to read in

  • 2
    How do you know that the lines in the file are 100 bytes long? – ad absurdum Jul 08 '17 at 12:11
  • in the question he uses an array of 100 byres for a line so if he knows that the line is 100 bytes so he can move 200 bytes to the third line :D – Mohamed Ahmed gebrel Jul 08 '17 at 13:15
  • 1
    In the posted code a line is read into an _array_ that holds 100 bytes; this does not mean that the lines in the file are 100 bytes long. They may be shorter or longer. Given that posted code does not attempt to handle cases where lines are longer than 100 bytes, it may be safe to assume that _maximum_ line length is 100 bytes. If lines are shorter, your solution will not work as expected; and OP has given us no reason to expect this special condition. – ad absurdum Jul 08 '17 at 13:25
  • i think while loop will be a good solution to handle cases that the line is more or less than 100 byte but if he is sure that the line is 100 bytes my code is enough. – Mohamed Ahmed gebrel Jul 08 '17 at 13:37
  • 1
    'in the question he uses an array of 100 byres for a line so if he knows that the line is 100 bytes' ....sorry, that conclusion makes no sense to me:( – ThingyWotsit Jul 08 '17 at 18:35