Separating and reprinting a big string
2 次查看(过去 30 天)
显示 更早的评论
I have a text file with about 45000 entries all on one line seperated by "//"
I would like to read this huge line from juneweather.txt, seperate it into seperate strings and write them onto a new file, each one on a new line. i keep getting the error
Error using fwrite
Cannot write value: nonscalar strings are unsupported.
Error in weather02 (line 16)
fwrite(fid1, john);
fid1=fopen('JuneWeather2.txt','at');
fid2=fopen('JuneWeather.txt'); %.... open the file, MATLAB assigns an ID
line=fgets(fid2);
greg=strsplit(line,'//');
%disp(greg);
for i=1:length(greg)
corey = {greg(i),'\r'};
john = string(corey);
fwrite(fid1, john);
end
Any ideas? thanks so much!
0 个评论
采纳的回答
Robert U
2019-9-26
Hi bws1007:
The string to write needs to be scalar. The command fwrite() is used to write into binary format, thus it does not make any difference whether it is in one line or not. You would not see the difference unless you read the binary file and parse the string including any formating commands as '\n'. If you want to write text files, use fprintf(). Below you find a small example using your variable names (maybe you consider to change these names):
TestString = 'Do not write strings // in one line // because it annoys // the user.';
greg=strsplit(TestString,'//');
corey = cellfun(@(cIn) [cIn,'\n'],greg,'UniformOutput',false);
john = string(corey);
% Binary file
fileID = fopen('myTestFile.bin','w');
arrayfun(@(dIn) fwrite(fileID,dIn),john);
fclose(fileID);
% test read
TestID = fopen('myTestFile.bin','r');
TestInput = fread(TestID,'*char')';
fclose(TestID);
% text file
fileID = fopen('myTestFile.txt','w');
fprintf(fileID,'%s\n',strrep(john,'\n','')');
fclose(fileID);
% you can check the text file output with your text editor or matlab
Kind regards,
Robert
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Environment and Settings 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!