Reading text file in Matlab results in unknown spa

2019-08-30 16:09发布

I am trying to read a text/csv file in Matlab.The file looks like:

VolumeDisplacement,9783.47
CenterOfBuoyancy,-0.732585,3.16072e-14,-3.09939
WettedSurfaceArea,2709.66
WaterlineLength,102.156
MaximumWaterlineBeam,20.76
WaterPlaneArea,1774.4
CenterOfFloatation,-6.32016,1.00108e-11,0

The file is generated using vbscript in Rhinoceros. I am using the standard method given in the help file, but encountering a weird problem.

filename = 'RhinoResult.txt';
fid = fopen(filename);
line = fgetl(fid);
tline = textscan(line,'%s%d','Delimiter',',');
VolumeDisplacement=tline{2};

But, my results are not as expected. The tline is storing the strings with a space between each character. Also, there are two unknown characters (ÿþ) at the beginning.

tline{1} = 'ÿþV o l u m e D i s p l a c e m e n t '

The VBScript used to create the textfile looks like this:

Sub writeResult(arrResults, filePath, fileName)
    Dim objFSO,objFile

    Const ForWriting = 2

    Set objFSO = CreateObject("Scripting.FileSystemObject")
    Set objFile = objFSO.CreateTextFile(filePath & fileName, _ 
    ForWriting, True)

    objFile.Write "VolumeDisplacement," & arrResults(0)
    objFile.Writeline
    objFile.Write "CenterOfBuoyancy," & arrResults(1)
    objFile.Writeline
    objFile.Write "WettedSurfaceArea," & arrResults(2)
    objFile.Writeline
    objFile.Write "WaterlineLength," & arrResults(3)
    objFile.Writeline
    objFile.Write "MaximumWaterlineBeam," & arrResults(4)
    objFile.Writeline
    objFile.Write "WaterPlaneArea," & arrResults(5)
    objFile.Writeline
    objFile.Write "CenterOfFloatation," & arrResults(6) 
    objFile.Writeline

    objFile.Close

End Sub

Can someone help me with this?

Thanks, Amitava

1条回答
甜甜的少女心
2楼-- · 2019-08-30 16:17

If you look at the docs, you'll see

object.CreateTextFile(filename[, overwrite[, unicode]])

Your

Set objFile = objFSO.CreateTextFile(filePath & fileName, _ 
    ForWriting, True)

(probably mis-copied from a .OpenTextFile call) fools .CreateTextFile into using Unicode (evidence: BOM, 'spaces').

So use .CreateTextFile correctly to create (and write to) an ANSI file:

Set objFile = objFSO.CreateTextFile(filePath & fileName, True, False)
查看更多
登录 后发表回答