tags:

views:

59

answers:

3

How do I read input one string at a time to call another function in C. I thought this would work, but my output hangs:

#define BUFFMT "%255"
#define LINE_LEN 256
#define START_COUNT 1

// filename is declared in the main file elsewhere.  I know the file opens since I tried an //old method I use to read one line at time using fgets, but I didn't know how to do one //string at a time.  Thanks.
FILE *OpenFile(const char *fileName)
{
    FILE *fptr;
    if ((fptr = fopen(fileName, "r")) == NULL) {
        fprintf(stderr, "Error opening file %s, exiting...",  fileName);
        exit(EXIT_FAILURE);
    }
    return fptr;
}

LIST *CreateList(FILE *fp) 
{
    char buf[LINE_LEN];

    while (scanf(BUFFMT"s", buf) != EOF) {
        printf("%s: \n", buf);
    }
}
+2  A: 

Try this instead of your scanf:

fgets (buf, sizeof (buf), fp)
sha
A: 

Have you tried using fgets()

fgets()

fgets() reads up to size-1 characters from stream and stores them in buffer. fgets() stores the null character ('\0') after the last character read into the buffer and returns 'buffer' if everything works fine, or NULL on error or end of file.

astander
+4  A: 

scanf() is going to read from the terminal, so it's going to hang waiting for you to type in your input. Use fscanf(fp, BUFFMT"s", buf) instead.

Eric Warmenhoven