简体   繁体   中英

Open text files in matlab and save them from matlab

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 ?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM