How to not overwrite the lines of a file when in a loop?

126 views Asked by At

I have a text file which has blocks of data. The blocks are a struct. Each block has a number of records, in my example each block has 12 records. What I want to do is to sort each block and write it in another file that I've called sortedFile This is my code, I didn't post the whole code because it would be too much.

while(counter < numOfBlocks){
    fread(buffer, 1, sizeof(block_t), fileOp);

    //get the blocks
    //buffer->blockid = firstBlock;

    for(uint i = 0; i < buffer->nreserved; i++){
        for(uint j = i; j < buffer->nreserved; j++){
            if(buffer->entries[i].num > buffer->entries[j].num){
                smallest = buffer->entries[j].num;
                buffer->entries[j].num = buffer->entries[i].num;
                buffer->entries[i].num = smallest;

                //keep the record id's
                uint smallestID = buffer->entries[j].recid;
                buffer->entries[j].recid = buffer->entries[i].recid;
                buffer->entries[i].recid = smallestID;

                fwrite(&buffer, 1, sizeof(block_t), sortedFile);
                //fscanf(sortedFile,"Record id: %d, Num: %d", buffer->entries[i].recid, smallest);
            }

        }


    }
    counter++;
}

This while loop is doing exactly what I want. The blocks get sorted by their buffer->entries[].num field and it is written in the sortedFile then I update the counter and I start the for loop again and I have the impression that the for loop is writing the data over the data from the previous loop. Here is how I print out the contents of sortedFile. As a result I get only the sorted values of the last block.

  //print out contents of sortedFile
int z = 0;

printf("This is the sorted file: \n");
while(z < reserved){
    fread(buffer, 1, sizeof(block_t), sortedFile);
    printf("Block id: %d, Record id: %d, Num: %d\n", buffer->blockid, buffer->entries[z].recid,
                                                         buffer->entries[z].num);
    z++;
}

fclose(sortedFile);

How can I show my program to show to the next segment of the file to write the new data? I'm thinking of using fwrite with some sort of pointer of the size of the block, that gets updated everytime the loop is being run, but I'm not that experienced and I can't get it right.

0

There are 0 answers