when I use fwrite to save a string with various ASCII characters, the resulting texfile changes some characters
7 次查看(过去 30 天)
显示 更早的评论
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 个评论
采纳的回答
Cris LaPierre
2018-11-21
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
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 String Parsing 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!