Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Code to compare 2 files and list the line and character that differ. It doesn't compare them line-by-line rather character by character, but keeps track of the line number and loads the file into blocks of 4Kbytes.</p> <pre><code>#define BLOCKSIZE 4096 char file1charbuf[BLOCKSIZE]; //4096 character buffer in stack char file2charbuf[BLOCKSIZE]; int linepos=1, charpos =1, i, b1, b2 ; int file1 = open("1.txt", O_RDONLY); int file2 = open("2.txt", O_RDONLY); do{ b1=read(file1, file1charbuf, BLOCKSIZE); b2=read(file2, file2charbuf, BLOCKSIZE); for(i=0; i &lt; b1 &amp;&amp; i &lt; b2; ++i){ if (file1charbuf[i]!=file2charbuf[i]){ printf("differ: char %i, line %i\n",charpos,linepos); close(file1); close(file2); exit(1); } if (file1charbuf[i] == '\n'){ ++linepos; charpos=0; } ++charpos; } }while( (b1 == BLOCKSIZE || (file1==STDIN &amp;&amp; file1charbuf[b1-1] != 0x26)) &amp;&amp; (b2 == BLOCKSIZE || (file2==STDIN &amp;&amp; file2charbuf[b2-1] != 0x26)) ); if (b1 != b2) printf("One bigger than the other\n"); close(file1); close(file2); </code></pre> <p>About reading from STDIN:</p> <p>read() from stdin unblocks when you press enter. At that time only the characters you typed so far are availiable to be read. This means that b1 will equal to the characters you typed so far. The <code>do-while</code> condition will fail because read didn't read all the 4096 bytes it requested, which will make it think that it's because the stream has ended. To continue reading after the \n we have to change the while condition so that if the file descriptor we are reading is STDIN, to continue reading unless the last character we read is the stream end character which i think is <code>0x26</code>. I hope that ^D will also unblock read() in the same way enter does.</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