开发者

Read one string at a time from a file in C

开发者 https://www.devze.com 2022-12-21 07:18 出处:网络
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:

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

// filenam开发者_如何学编程e 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);
    }
}


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.


Try this instead of your scanf:

fgets (buf, sizeof (buf), fp)


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号