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;
}
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\nwith a null terminator: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 byfgets().When printing strings I find it useful to place the string inside
[]to make the content of the string clearer: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 variablebuff: this is an error and is undefined behaviour. A new buffer will need to be dynamically allocated, usingstrdup()if available ormalloc()andstrcpy()otherwise:the caller of
webroot()mustfree()the returned value. Arrange thatNULLis returned if a failure occurs.