views:

40

answers:

2

I am creating a .dat file with headers and data in Matlab like this:

%# Define the name of the file where data is to be written
dataName = 'sampledata_models_poro_reference_truth';

%# open the file
fid = fopen('sampledata_models_poro_reference_truth.dat','w');

%# start writing. First line: title
fprintf(fid,'%s\n',dataName); %# don't forget \n for newline. Use \n\r if yow want to open this in notepad

%# write number of models
fprintf(fid,'%i\n',nModel)

%# loop to write the rest of the header
for iModel = 1:nModel
    fprintf(fid,'%s_%i\n',dataName,iModel);
end

%# use your favorite method to write the rest of the data.
%# for example, you could use fprintf again, using \t to add tabs
%# create format-string
%# check the help to fprintf to learn about formatting details
formatString = repmat('%f\t',1,nModel);
formatString = [formatString(1:end-1),'n']; %# replace last tab with newline

%# transpose the array, because fprintf reshapes the array to a vector and
%# 'fills' the format-strings sequentially until it runs out of data
fprintf(fid,formatString,sampledata_models_poro_reference_truth');

%# close the file
fclose(fid);

The file gets created, however when I try opening it from the folder where it is saved, then I get the error as shown in the snapshot below. This error occurs even when Matlab is closed. I can only open it as a text by right clicking on the file through the Matlab's current directory window.alt text

Why is this happening and how to resolve it?

+1  A: 

This is not supposed to happen, and, in fact, doesn't happen when I try your code on my machine (OS X, R2010a). In other words, I strongly doubt that there is any problem with the Matlab code.

Try restarting Windows, then the problem should go away for newly created, differently named files.

Jonas
I restarted the windows and tried again then it was working. Ran the code again (2 of them) and checked .dat files associated with them and still they were opening. However now suddenly again the files are showing similar error after running the code.
Harpreet
@Harpreet: In case its not MATLAB, you could use the tool I mentioned above (Unlocker), as it will tell you exactly which process has a locking handle on the .dat file, and allow you to release it. I use it all the time, its much easier than having to restart every time :)
Amro
+1  A: 

You could try:

fclose('all')

to close all open files.

Amro
@Amro: Thanks. However I am trying again and sometimes it does open and sometimes it doesn't. Though in my last multiple tries it has opened without any error.
Harpreet
I think fclose('all') solves the problem.
Harpreet

related questions