I don't like the function at all. It would be better IMO to read the file a character at a time and watch for the \n rather than reading an entire buffer, finding the \n and seeking back to reset the file pointer. Much less work.
WaltP
Posting Sage w/ dash of thyme
10,505 posts since May 2006
Reputation Points: 3,348
Solved Threads: 944
So, can you see what is wrong with the program?
I'd wager that it has something to do with your math. You're using the size of the buffer rather than the number of extracted characters to calculate the seek offset. Compare and contrast:
char *a3_fgets_2(char *str, int num, int fd)
{
int n = read(fd, str, num - 1);
int i = 0;
if (n <= 0)
return NULL;
while (i < n) {
if (str[i++] == '\n')
break;
}
lseek(fd, i - n, SEEK_CUR);
str[i] = '\0';
return str;
}
Narue
Bad Cop
15,460 posts since Sep 2004
Reputation Points: 6,464
Solved Threads: 1,401