Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Since this apparently isn't homework, here's some sample code of how I'd do it. I'm just allocating a huge block of memory for the entire file, since you're going to read the whole thing eventually anyway, but if you're dealing with large files it's usually better to handle them a line at a time.</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; int main(int argc, char *argv[]) { // first, get the name of the file as an argument if (argc != 2) { printf("SYNTAX: %s &lt;input file&gt;\n", argv[0]); return -1; } // open the file FILE* fp = fopen(argv[1], "r"); if (fp == NULL) { printf("ERROR: couldn't open file\n"); return -2; } // seek to the end to get the length // you may want to do some error-checking here fseek(fp, 0, SEEK_END); long length = ftell(fp); // we need to seek back to the start so we can read from it fseek(fp, 0, SEEK_SET); // allocate a block of memory for this thing // the +1 is for the nul-terminator char* buffer = malloc((length + 1) * sizeof(char)); if (buffer == NULL) { printf("ERROR: not enough memory to read file\n"); return -3; } // now for the meat. read in the file chunk by chunk till we're done long offset = 0; while (!feof(fp) &amp;&amp; offset &lt; length) { printf("reading from offset %d...\n", offset); offset += fread(buffer + offset, sizeof(char), length-offset, fp); } // buffer now contains your file // but if we're going to print it, we should nul-terminate it buffer[offset] = '\0'; printf("%s", buffer); // always close your file pointer fclose(fp); return 0; } </code></pre> <p>Whew, it's been a while since I've written C code. Hopefully people will chime in with helpful corrections/notices of massive problems. :)</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