views:

360

answers:

3

In Matlab, after creating a certain number of lines and printing them to a file, I have the need to delete a line and rewrite the rest of the data to that same file. When I do so, the new data overwrites the previous data, but since the data is shorter than the original, there are still remnants of the original data. Does anyone have any idea what the best/most efficient way to delete that extra data is?

Here is a simplified example of what I'm trying to do:

fid = fopen('file.txt','w');  
for i=1:10  
    fprintf(fid,'%i\r\t',i);  
end  
frewind(fid);  
for i=3:5  
    fprintf(fid,'%i\r\t',i);  
end  
fprintf(fid,'EOF');  
fclose(fid);

I've looked all over, but I can't seem to find the solution to my question. Any suggestions?

A: 

Printing "EOF" won't work - nice try!

There are Unix system calls truncate and ftruncate that will do that, given either a file descriptor (truncate) or handle (ftruncate) in the first argument and a desired length in the second.

I'd try and see if Matlab supports ftruncate. Failing that... if worst came to worst you could copy-write the file to a new file, stopping and closing the new file when you hit what you consider the end of data.

Carl Smotricz
Yeah, I printed "EOF" for my own reference when I open the file the next time to read data in. thanks though. And the answer is No, Matlab (at least in Windows) doesn't seem to support ftruncate.
ServAce85
A: 

To follow up on Carl Smotricz's suggestion of using two files, you can use MATLAB's DELETE and MOVEFILE commands to avoid system calls:

fid = fopen('file.txt','wt');
for i=1:10
    fprintf(fid,'\t%i\r',i);
end
fclose(fid);

fid = fopen('file.txt','rt');
fidNew = fopen('fileNew.txt', 'wt');
for i = 1:2
    s = fgetl(fid);
    fprintf(fidNew, '%s\r', s);
end
for i=4:10
    fprintf(fidNew, '\t%i\r', i);  
end
fclose(fid);
fclose(fidNew);

delete('file.txt');
movefile('fileNew.txt', 'file.txt')
mtrw
At this point I would prefer not to use more than one file. Thanks for the info if I do decide to go that route.
ServAce85
+3  A: 

Without using any temp files, you can do the following:

fid = fopen('file.txt', 'wt');
for i=1:10
    fprintf(fid, '%i\n', i);
end
frewind(fid);  
for i=3:5
    fprintf(fid, '%i\n', i);
end
pos = ftell(fid);             % get current position in file
fclose(fid);

% read from begining to pos
fid = fopen('file.txt', 'r');
data = fread(fid, pos);
fclose(fid);

% overwite file with data read
fid = fopen('file.txt', 'w');
fwrite(fid, data);
fclose(fid);
Amro

related questions