I'm working on an assignment where part of it is to read from stdin using the system function read(), and then print the last 10 lines and so far I've got this:
int tailSTD()
{
char *lines = malloc(1);
char buffer[10];
int cmdCount = 0, buffCount, rState;
while((rState = read(STDOUT_FILENO, buffer, 10)) > 0)
{
if(rState < 0)
{
if(errno == EINTR) rState = 0;
else
{
perror("read()");
return 0;
}
}
else if (rState == 0) break;
lines = realloc(lines, strlen(lines) + strlen(buffer));
for(buffCount = 0; buffCount < strlen(buffer); buffCount++)
{
lines[cmdCount] = buffer[buffCount];
cmdCount++;
}
}
printf("do we get this far?");
printSTDLines(lines);
return 0;
}
The problem is that I get a segmentation fault somewhere along the loop and I\m not sure where, this worked with fgets(), and I simply modified it just because it just HAS to be done with read(). It's probably very messy, for which I apologize, but it just has to be done in this manner. I know the problem is here, because it never gets to the last printf before printSTDLines.
Here's printSTDLines if you need it:
void printSTDLines(char *lines)
{
int lineCount = strlen(lines), newLineCount = 0;
while(newLineCount < 10)
{
if(lines[lineCount] == '\n')
{
newLineCount++;
}
lineCount--;
}
int readSize = strlen(lines) - lineCount;
for(lineCount = readSize; lineCount < sizeof(lines); lineCount++)
{
write(STDOUT_FILENO, &lines[lineCount], 1);
}
}