Search code examples
cfile-iofgets

Reading from a configuration file


I'm working on reading a path from a simple configuration file and store it in to a char array using C language. I came up with a way to do that but have a problem with retrieving the path without white spaces attached the end of it. Please help me to find a better way of doing this.

char* webroot(){
 FILE *in = fopen("conf", "rt");
 char buff[1000];
 fgets(buff, 1000, in);
 printf("first line of \"conf\": %s\n", buff);
 fclose(in);

 return buff;
}

Solution

  • It is not a sequence of whitespace characters at end but the new-line character, as fgets() includes it in the returned buffer: replace the \n with a null terminator:

    /* fgets() will not read the new-line if
       there is not sufficient space in the buffer
       so ensure it is present. */
    char* nl_ptr = strrchr(buff, '\n');
    if (nl_ptr) *nl_ptr = '\0';
    

    It may appear as though there is a sequence of whitespace characters because of the apparent line wrapping on stdout, but it is due to the presence of the new-line character read by fgets().

    When printing strings I find it useful to place the string inside [] to make the content of the string clearer:

    printf("first line of \"conf\": [%s]\n", buff);
    

    this would make the presence of the new-line character obtained by fgets() more visible.

    Note that the function webroot() is returning the address of the local variable buff: this is an error and is undefined behaviour. A new buffer will need to be dynamically allocated, using strdup() if available or malloc() and strcpy() otherwise:

    return strdup(buff);
    

    the caller of webroot() must free() the returned value. Arrange that NULL is returned if a failure occurs.