0
votes

I would like to open a text file in Matlab and overwrite part of it. I dont want to store the data since its a huge file, but I want to skip the first n=213021 lines by using fgetl (or similar command), and then delete the rest and overwrite it with my data. I am trying with the code below but for some strange reason the command fprintf does not write anything. I am printing on screen the lines skipped with getl and it seems like I am in the right location. However, nothing is written with fprintf. Here a minimal example:

data =50:10:100;
n=4; 
fid = fopen('example.txt','r+')
for i=1:n
     fgetl(fid); %skips first n lines
end
fprintf(fid,'%i \r\n',data);
fclose(fid)

The example file initially reads:

1
2
3
4
5
6
7
8
9
10

And after the above code is run it should read:

1
2
3
4
50
60
70
80
90
100

but the text file is actually unchanged. Any clue?

1
what does variable 'data' represents inside fprintf? - redumpt
Ok sorry my bad I thought it was clear it was just an example with "data" being any vector. I rewrote it by using a minimal example that can be tested and that does not work. - Millemila

1 Answers

2
votes

As noted in the documentation, you have to call fseek between read and write operations.

data =50:10:100;
n=4; 
fid = fopen('example.txt','r+')
for i=1:n
     fgetl(fid); %skips first n lines
end

fseek(fid,0,'cof');

fprintf(fid,'%i \r\n',data);
fclose(fid)