title: How to copy text file to string in C?
body: <p>I need to copy the contents of a text file to a dynamically-allocated character array. </p>
  
  <p>My problem is getting the size of the contents of the file; Google reveals that I need to use <code>fseek</code> and <code>ftell</code>, but for that the file apparently needs to be opened in binary mode, and that gives only garbage.</p>
  
  <p>EDIT: I tried opening in text mode, but I get weird numbers. Here's the code (I've omitted simple error checking for clarity):</p>
  
  <pre><code>long f_size;
  char* code;
  size_t code_s, result;
  FILE* fp = fopen(argv[0], "r");
  fseek(fp, 0, SEEK_END);
  f_size = ftell(fp); /* This returns 29696, but file is 85 bytes */
  fseek(fp, 0, SEEK_SET);
  code_s = sizeof(char) * f_size;
  code = malloc(code_s);
  result = fread(code, 1, f_size, fp); /* This returns 1045, it should be the same as f_size */
  </code></pre>