Question

I need to write the Solaris the 'line' application on Solaris, which is very simple, on Linux. It was developed for scripting, it takes one line of stdin and outputs it to stdout. I wrote an extraordinarily simple C program to do this. I used both getline and fgets and they produce the same outcome:

int main(int argc, char* argv[])
{
    char buf[256];
    char* line = NULL;

    if (fgets(line, 256, stdin) != NULL)
    //if (getline(&line, &len, stdin) != -1)
    {
        printf("%s", line);
    }
    return EXIT_SUCCESS;
}

The C-Shell script, loop_file looks like this:

#!/bin/csh -f
while(1)
    set line = `app`
    echo "Got Line : $line"
end

I kick off the process using the following: ./loop_file < textFile.txt

It's a large file, the first line is printed out just but the next line is almost 4096 characters after, the third line is almost 4096 after that, etc. It is not a line-by-line read. I've even tried forgetting using C and using awk in the while loop instead.

Any ideas?

By the way, don't say - don't use CSH - it's legacy code I'm required to port :)

while(1)
set line = `app`

    set name = $line[0];
    set address = $line[1];
    set purpose = $line[2];
end
Was it helpful?

Solution

stdin is buffered which could be the reason why some of the lines from the text file are missed out. You could possibly make stdin unbuffered using setvbuf(fd, NULL, _IONBF, 0) or equivalent before fgets call in your C program and address this issue.
Alternatively, you can read character by character following the suit of line utility. Maybe something on the lines of :

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

int main(void)
{
    char c;
    while(read(STDIN_FILENO , &c, 1) > 0 && c != '\n')
        putchar(c);
    return  EXIT_SUCCESS;
}

Hope this helps!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top