简体   繁体   中英

Reading writing from offset

bool CReadWrite::write(unsigned long long offset, void* pvsrc, unsigned long long nbytes)
{   int WriteResult;

    pFile = fopen("D:\\myfile.bin","wb");

    if (!pFile){   
        puts("Can't open file"); 
        return false;
    }

    //offset = fseek(pFile,offset,

    WriteResult = fwrite (pvsrc, 1, nbytes, pFile);

    if (WriteResult == nbytes){   
        puts("Wrote to file");
        fclose(pFile);
        return true;
    }
    else{   
        puts("Unable to write to File."); 
        fclose(pFile);
        return false;
    }   
}

This is my class function so far. I'm basically opening a file, checking to see if it did indeed open if not get out. Writes the file, checks to see if the file see if the file was indeed written to returns true. else return false. As you can tell by my parameters, I'm looking to create an offset where I can give a particular offset ie 10, and start from 10 and then from there write. I know for sure I need to use fseek but I can't assume that I'm at the beginning of the file or anywhere in the file. Im pretty sure i need to use SEEK_SET but I may be wrong. Any thoughts on implemented the above desires? Thanks.

If you're using fopen without the append setting (as you are, "wb" creates an empty file), you can assume you're at the beginning.

Regardless, SEEK_SET sets the position to the given offset from the beginning.

If the file doesn't have the offset that you want to seek to (as it is in your case), then the question is what are you required to do? If just pad - then write offset padding bytes, and then your content, otherwise maybe you wanted to use "a" and not "w". "w" truncates the existing content of the file, while "a" opens for append and sets position to the end of the existing content.

More details here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM