when I use fwrite to save a string with various ASCII characters, the resulting texfile changes some characters
7 views (last 30 days)
Show older comments
Ricardo Fuertes
on 20 Nov 2018
Commented: Ricardo Fuertes
on 21 Nov 2018
Im trying to make a LZ78 coder, and when I want to save a string of characters using fwrite, the resulting .txt file is slightly different from the original string.
For instance, the string token_fin contains, as the first 10 characters, the following characters (here with their ASCII value):
24 136 2 217 88 52 134 122 216 24
When I use the next lines:
fwrite(write_file, token_fin, '*char');
fclose(write_file);
Then, when I use the next lines to open the file created previosly
read_file = fopen('LZ78_Output.txt','r');
labuffer = fread(read_file, '*char');
the first 10 characters are theese:
24 26 2 217 88 52 26 122 216 24
As you can see, characters 136 and 134 are replaced with 26.
Im not sure why this is happening, if anyone can help me I would really apreciate it.
0 Comments
Accepted Answer
Cris LaPierre
on 21 Nov 2018
I think the issue is that you are using fwrite with *char. According to the precision table, this allocates 8 bits for the encoding. 8 bits allows for numbers from 0-127. Any value greater than that gets wrapped around in some way I have figured out yet. You need to set an appropriate machine format and enoding in fopen. It depends on where you are and your machine what you use. I used (..., 'n', 'ISO-8859-1').
Here is an approach that works for me.
token_fin = [24 136 2 217 88 52 134 122 216 24];
write_file = 'LZ78_Output.txt';
fid = fopen(write_file,'w+','n', 'ISO-8859-1');
fwrite(fid, token_fin, 'char');
fclose(fid);
read_file = fopen('LZ78_Output.txt','r','n', 'ISO-8859-1');
labuffer = fread(read_file, 'char');
double(labuffer)'
ans = 1×10
24 136 2 217 88 52 134 122 216 24
More Answers (0)
See Also
Categories
Find more on String Parsing in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!