Click here to Skip to main content
15,918,050 members
Please Sign up or sign in to vote.
3.00/5 (2 votes)
See more:
Help please,

I have created a file and I can write to that file and can even append it.

so my question is:

Before appending some data to that file I wanted to check if that file has the same data on the file,
If it has the same data then I don't want to write on that file else write to that file.

Help appreciated and program codes most honored.
Posted
Updated 16-May-12 18:25pm
v2

hi
Move the pointer to end and start of the file and get the position using tellp() or tellg() methods(these are c++ methods you have to look for c methods)
Once you have the position calculate the difference.
If you'll get it to be zero then there is no content written in it.

i Have found one link may be it helps you but i'm not sure


http://stackoverflow.com/questions/238603/how-can-i-get-a-files-size-in-c[^]

Thanks
 
Share this answer
 
To compare if the file data is identical to your data in memory:

1) Get the file size (for example you could use GetFileSize in C++)
2) If the file size is not the same as the size of your mem data, go to point 4
3) If the file and mem data are the same size, then open the file for read (see Note 1) and compare with your data in memory (See note 3). If you find a mismatch before the end of the file is reached, go to step 4. Otherwise, close the file and exit without overwriting (data identical).
4) Overwrite the file with mem data. Easiest way, close and reopen file with Create/Write attribute and then write the whole chunk of your memory data to file.

Note1 : my preference would be to open file in step 3 for read access only and close and re-open it in step 4. But you can also open it in read/write mode and avoid closing/reopening. A matter of personal taste.

Note2: I assumed that if they are different size, even if all available bytes of data match, then you want to overwrite as well.

Note3: You can either read and compare byte-by-byte, or, alternatively read the whole file into another buffer and do mem compare. First would not require any additional memory allocation so I would go for it if speed is not an issue.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month


CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900