UNIX file read and writing over not writing
<p>I'm trying to find a hit in a file and modify it by writing over. But the modification of the field <code>Effectue</code> (from the structure <code>TRAVAIL</code>) is not applying. I checked that I was replacing the right occur (commented part) but when I call again the function I'm still getting the first occurence with <code>Effectue</code> set to <code>false</code>.</p>

<pre><code>TRAVAIL RechercheProchainTravail() {
    int i, fp;
    TRAVAIL travailRetour;

    if ((fp = open("Travaux.dat", O_RDWR | O_CREAT | O_TRUNC, 0664)) == -1) {
        perror("Err open Travaux.dat");
        exit(1);
    }

    // init
    for (i = 0; TravauxInit[i].IndiceLieu &gt; 0; i++)
        write(fp, &amp;TravauxInit[i], sizeof(TRAVAIL));

    // remise au debut
    lseek(fp, 0, SEEK_SET);

    //lecture
    for (i = 0; TravauxInit[i].IndiceLieu &gt; 0; i++) {
        read(fp, &amp;travailRetour, sizeof(TRAVAIL));
        if (travailRetour.Effectue == false) {
            travailRetour.Effectue = true;
            lseek(fp, -sizeof(TRAVAIL), SEEK_CUR);
            /*read(fp, &amp;travailRetour, sizeof(TRAVAIL));
            Trace(" indice; %d effect %d", travailRetour.IndiceLieu, travailRetour.Effectue);
            lseek(fp, -sizeof(TRAVAIL), SEEK_CUR);*/
            write(fp, &amp;travailRetour, sizeof(TRAVAIL)); 
            break;
        }
    }
    close(fp);

    return travailRetour;
}
</code></pre>

<p><strong>EDIT:</strong> 
I changed the open to prevent the file from being truncated as peter noticed, but the issue is still the same, I still access the first occurence because the write don't change the Effectue field value.</p>

<p>Here is my code edit:</p>

<pre><code>    if (access( "Travaux.dat", F_OK ) != -1) { // si existe ouvrir
        if ((fp = open("Travaux.dat", O_RDWR, 0664)) == -1) {
            perror("Err open Travaux.dat");
            exit(1);
        }
    } else { // sinon creer
        if ((fp = open("Travaux.dat", O_RDWR | O_CREAT | O_TRUNC, 0664)) == -1) {
            perror("Err open Travaux.dat");
            exit(1);
        }
    }
</code></pre>

<p>And it is not a <code>lseek</code> issue, because the read test displays the right occurrence.</p>