Note that there are some explanatory texts on larger screens.

plurals
  1. POUnderstanding String assignments in C
    text
    copied!<p>Okay I've read through a massive amount of of the answers here on SO, and many other places but I just can't seem to grasp this simple function. Please forgive me for something so simple I haven't done c/c++ code in over 8 years and I'm very much trying to re-learn, so please have patience...</p> <p>I've tried many different ways to do this from assigning a string through a function param by shifting in the value to just straight returning it, but nothing seems to work within the while. I also get no errors during compile time, but I do get segfaults at runtime. I would very much like to find out why the following function does not work... I just don't understand why the else returns fine as type char *content, but strcat(content, line); does not. Even though the man pages for strcat shows that strcat's definition should be (char *DEST, const char *SRC). As I currently understand it trying to do a cast to a const char on the line variable within the while would just return an integer to the pointer. So I'm stumped here and would like to be educated by those who have some time!</p> <pre><code>char * getPage(char *filename) { FILE *pFile; char *content; pFile = fopen(filename, "r"); if (pFile != NULL) { syslog(LOG_INFO,"Reading from:%s",filename); char line [256]; while (fgets(line, sizeof line, pFile) != NULL) { syslog(LOG_INFO,"&gt;&gt;&gt;&gt;&gt;&gt;&gt;Fail Here&lt;&lt;&lt;&lt;&lt;&lt;&lt;"); strcat(content, line); } fclose(pFile); } else { content = "&lt;!DOCTYPE html&gt;&lt;html lang=\"en-US\"&gt;&lt;head&gt;&lt;title&gt;Test&lt;/title&gt;&lt;/head&gt;&lt;body&gt;&lt;h1&gt;Does Work&lt;/h1&gt;&lt;/body&gt;&lt;/html&gt;"; syslog(LOG_INFO,"Reading from:%s failed, serving static response",filename); } return content; } </code></pre> <p>Very much appreciate all the great answers in this post. I would give everyone in the discussion a checkmark but unfortunately I can't...</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload