4

I'm trying to build a C codebase using emscripten, and it goes through an abstraction layer for all of its I/O calls. It's not doing what I'd expect, so I tried a simpler test using a getline routine from here on StackOverflow:

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

// From: https://stackoverflow.com/a/314422/211160
char * getline_litb(void) {
    char * line = malloc(100), * linep = line;
    size_t lenmax = 100, len = lenmax;
    int c;

    if(line == NULL)
        return NULL;

    for(;;) {
        c = fgetc(stdin);
        if(c == EOF)
            break;

        if(--len == 0) {
            len = lenmax;
            char * linen = realloc(linep, lenmax *= 2);

            if(linen == NULL) {
                free(linep);
                return NULL;
            }
            line = linen + (line - linep);
            linep = linen;
        }

        if((*line++ = c) == '\n')
            break;
    }
    *line = '\0';
    return linep;
}

int main() {
  puts(getline_litb());
  return 0;
}

Compiled under gcc or clang this works fine. It reads a string in until you press enter, and returns that string. But when I compile it with:

emcc test.c -o test.bc
emcc test.bc -o test.js
node test.js

It thinks there's a line feed entered, so it prints a blank line and doesn't give me a chance to input. Any ideas?

Community
  • 1
  • 1

1 Answers1

1

I have had a similar problem with this before but it happened to me after I didn't properly clean out the stdin buffer. Try calling fgetc() once or twice and then call it again for real. That could clean out some or all the data that may be left in the standard input buffer. If that dosen't work then I would printf() 'c' to the screen right after it is returned from fgetc().

John Vulconshinz
  • 1,088
  • 4
  • 12
  • 29
  • Very sorry for the (long) delay in commenting/upvoting. The issues have been picked up by others...and I will keep this Q&A on the map to see if they weigh in, because some progress has been made. So hoping they'll chime in here about what it is they did! – HostileFork says dont trust SE May 20 '15 at 02:36