title: What is the difference between memcmp, strcmp and strncmp in C?
body: <p>I wrote this small piece of code in C to test <code>memcmp()</code> <code>strncmp()</code> <code>strcmp()</code> functions in C.</p>
  
  <p>Here is the code that I wrote:</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  #include &lt;string.h&gt;
  
  int main() {
          char *word1="apple",*word2="atoms";
  
          if (strncmp(word1,word2,5)==0)
                  printf("strncmp result.\n");
          if (memcmp(word1,word2,5)==0)
                  printf("memcmp result.\n");
          if (strcmp(word1,word2)==0)
                  printf("strcmp result.\n");
  }
  </code></pre>
  
  <p>Can somebody explain me the differences because I am confused with these three functions?</p>
  
  <p>My main problem is that I have a file in which I tokenize its line of it,the problem is that when I tokenize the word "atoms" in the file I have to stop the process of tokenizing.</p>
  
  <p>I first tried <code>strcmp()</code> but unfortunately when it reached to the point where the word "atoms" were placed in the file it didn't stop and it continued,but when I used either the <code>memcmp()</code> or the <code>strncmp()</code> it stopped and I was happy.</p>
  
  <p>But then I thought,what if there will be a case in which there is one string in which the first 5 letters are a,t,o,m,s and these are being followed by other letters.</p>
  
  <p>Unfortunately,my thoughts were right as I tested it using the above code by initializing <code>word1</code> to "atomsaaaaa" and <code>word2</code> to atoms and <code>memcmp()</code> and <code>strncmp()</code> in the if statements returned 0.On the other hand <code>strcmp()</code> it didn't. It seems that I must use <code>strcmp()</code>.</p>