fread and fwrite application in reading file from disk

hello everyone, can you read data from disk (say a pdf file) with a precision other than uint8 (say integer*4) and then re-write the numerical array back into a meaningful file on the disk?

 Accepted Answer

input_data = fread(input_fid, '*uint32');
fwrite(output_fid, input_data);

5 Comments

Hi Walter, Thanks for the answer I think what I'm trying to validate the following scenario: reading a pdf file with precision= uint64, which reduces the number of numerical representations for that file (e.g a file that has 2000 uint8 numbers representing the bytes when read with higher precision becomes an array of N<2000 numbers each in the range of 0-2^64-1) how can I rewrite that array back to the disk such that its going to be interpreted the same way (as the pdf) Cheers,
Just like I showed, except switch to '*uint64' .
When you use fwrite(), if you do not specify an output format, it will look at the datatype of the data and use that format.
One subtle problem to watch out for if you start using the inputs as numeric values, is differences in which of the 4 8-bit bytes will be placed where in the numeric form. See the "BE" (big end) and "LE" (little end) and long-integer forms of the 'machineformat' option of fopen() and fread() and fwrite()
Hello again and thanks for the detailed answer, I think I figured out what the problem was: reading a file encoded in 8 bit chunks into 64 bit chunks you simply lose some information during the conversion! and I was not realizing this.
No information should be lost when you convert to 64 bit chunks. However, if you try to do arithmetic on 64 bit integers, and accidentally convert them to double precision in the process, then the result is only going to have 53 bits of precision instead of 64.
For example if you have
X = zeros(1024,1);
X(1:20) = fread(file, 20, '*uint64');
then the data would be read as uint64 but then converted to double to be stored in X because X is double. To fix you would use
X = zeros(1024,1,'uint64')
Hi! You are right! the information doesnt get lost, I just used the "typecast" function and casted the data back to uint8 (two bytes short than the original and had to be added to the end of the array) and then used fwrite to write it onto the hard and the pdf file was readable. I simply don't know where this can go wrong hence wont assume this might work for every file undergone the transitions. nonetheless thanks for the answer Walter
Regards, Siamack

Sign in to comment.

More Answers (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!