Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Consider the following cut-down example. You'll notice that the <code>getFileLength</code> function (a) doesn't actually read anything from the file and (b) makes use of the <code>fseek</code> and <code>ftell</code> functions - fseek is the function that you use to reposition the file-pointer when it reaches EOF.</p> <p>Imagine that you weren't printing the data, but doing something else with it. What if the file is a billion bytes long? We sure don't want to read 1,000,000,000 times from it just to determine its length!</p> <p>As for the use of calloc - it zero initializes the data it allocates. Since you're reading text, you want to ensure that the text is NULL-terminated. (NULL generally = 0, though I've seen evil macros that change this) This NULL terminator is also why I allocate 1 byte more than the file contains.</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; long getFileLength(FILE *input) { long result; long origPos = ftell(input); fseek(input, 0, SEEK_END); result = ftell(input); fseek(input, origPos, SEEK_SET); return result; } int main (void) { FILE *fp; long fileLen, numBytesRead; char *data; fp = fopen("main.cpp", "rb"); fileLen = getFileLength(fp); data = (char*)calloc(sizeof(char), fileLen+1); numBytesRead = fread(data, sizeof(char), fileLen, fp); if (numBytesRead != fileLen) printf("Error reading all bytes from file. Expected: %d, Read %d\n", fileLen, numBytesRead); else printf("%s", data); free(data); fclose(fp); } </code></pre>
 

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