Hi!

I am new to C and need some advice here. I have a solution to this problem but I still think there should be a way to do this more efficiently: I have a file where I have stored null-terminated strings including the '\0' char. I now want to read one string from the file stopping after the next '\0'. The strings in the file are at most 31 chars including the null char. I wrote this function to read one string from the file:

static int freadstr(FILE* fid, register char* str, size_t max_size)
{
    int c, count = 0;
    do {
        c = fgetc(fid);
        if (c == EOF) {
            /* EOF means either an error or end of file but
             * we do not care which. Clear file error flag
             * and return -1 */
            clearerr(fid);
            return -1;
        } else {
            /* Cast c to char */
            *str = (char) c;
            count++;
        }
    } while ((*str++ != '\0') && (count < max_size));
    return count;
}

Then in the calling function I do:

size = freadstr(fid, str, 32);
        if (size == -1) {
            /* End of file or file error */
            fprintf(stderr, "File error\n");
            return -1;
        } else if (size == 32) {
            /* Parse error, string was not null-terminated
             * within 31 bytes */
            fprintf(stderr, "Parse error\n");
            return -1;
        }

Is this not more complicated than it need to be?

Thanks,
Jonas

That looks like a good implementation to me, and without the comments its really quite short and sweet.

Had you terminated the strings with "\n" instead of "\0" then you could have simply called fgets() to read the strings back into memory.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.