Note that there are some explanatory texts on larger screens.

plurals
  1. POC file handling: Text doesn't append at the end of the file
    primarykey
    data
    text
    <p>The program should look at each line of <code>file1</code> and then, see if the exact same line exists in <code>file2</code>. If it does, then copy the line to a new file named output.</p> <p>Say, following are the content of files (It could be sentence but for simplicity, I've put numbers.)-</p> <pre><code> file1 file2 1 2 2 4 3 15 4 6 5 11 6 8 7 8 9 </code></pre> <p>Then <code>output</code> file should look like -</p> <pre><code> (Expected) output 2 4 6 8 </code></pre> <p>Inside shell I can see printf prints <code>output</code> as expected, but fprintf inverts the order and I don't understand why? Output that gets printed to the output file is-</p> <pre><code> output 8 6 4 2 </code></pre> <p>Here's the code -</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;string.h&gt; int main() { FILE *file1, *file2, *output; int c; /*Creating buffers where data will be stored for comparison*/ char buffer1[999], buffer2[999]; /*Settig the buffer characters array to 0*/ memset(buffer1, 0, sizeof(buffer1)); memset(buffer2, 0, sizeof(buffer2)); /*Open output file in "w" so that it clears the file*/ output = fopen("output", "w"); /*Open file1 and then save the line inside buffer1 (within while loop)*/ file1 = fopen("file1", "r"); /*Read each character in file until End Of Line*/ while((c = getc(file1)) != EOF) { int i = 0; /*Save each new line of file1 in buffer1 for comparison*/ while(c != '\n') { buffer1[i++] = c; c = getc(file1); } /*Open file2 and then save it's line in buffer2 (withing while loop)*/ file2 = fopen("file2", "r"); int ch; while((ch = getc(file2)) != EOF) { i = 0; while(ch != '\n') { buffer2[i++] = ch; ch = getc(file2); } /*Compare lines of file1 against each line of file2*/ if(strcmp(buffer1,buffer2) == 0) { /*Save similar lines in a file named output*/ output = fopen("output", "a"); fprintf(output,"%s\n", buffer2); printf("%s\n", buffer2); break; } /*Reset the buffer*/ memset(buffer2, 0, sizeof(buffer2)); } memset(buffer1, 0, sizeof(buffer1)); } /*Close the output file if there were any comparison made i.e. if file was opened*/ if(output != NULL) { fclose(output); } /*Close other files*/ fclose(file1); fclose(file2); return 0; } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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