Open text files in matlab and save them from matlab

爷,独闯天下 提交于 2019-12-23 05:46:26

问题


I have a big text file containing data that needs to be extracted and inserted into a new text file. I possibly need to store this data in an cell/matrix array ?

But for now, the question is that I am trying to test a smaller dataset, to check if the code below works.

I have a code in which it opens a text file, scans through it and replicates the data and saves it in another text file called, "output.txt".

Problem : It doesn't seem to save the file properly. It just shows an empty array in the text file, such as this " [] ". The original text file just contains string of characters.

%opens the text file and checks it line by line.
fid1 = fopen('sample.txt');
tline = fgetl(fid1);
while ischar(tline)
    disp(tline);
    tline = fgetl(fid1);
end
fclose(fid1);


% save the sample.txt file to a new text fie
fid = fopen('output.txt', 'w');
fprintf(fid, '%s %s\n', fid1);
fclose(fid);

% view the contents of the file
type exp.txt

Where do i go from here ?


回答1:


It's not a good practice to read an input file by loading all of its contents to memory at once. This way the file size you're able to read is limited by the amount of memory on the machine (or by the amount of memory the OS is willing to allocate to a single process).

Instead, use fopen and its related function in order to read the file line-by-line or char-by- char.

For example,

fid1 = fopen('sample.txt', 'r');
fid = fopen('output.txt', 'w');

tline = fgetl(fid1);
while ischar(tline)
    fprintf(fid, '%s\n', tline);
    tline = fgetl(fid1);    
end

fclose(fid1);
fclose(fid);

type output.txt

Of course, if you know in advance that the input file is never going to be large, you can read it all at once using by textread or some equivalent function.




回答2:


Try using textread, it reads data from a text file and stores it as a matrix or a Cell array. At the end of the day, I assume you would want the data to be stored in a variable to manipulate it as required. Once you are done manipulating, open a file using fopen and use fprintf to write data in the format you want.



来源:https://stackoverflow.com/questions/8689116/open-text-files-in-matlab-and-save-them-from-matlab

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!