Why does fopen fail the first time, but work the second time? - matlab

I am using Matlab to create a new file by calling
fid = fopen(filename,'w')
since filename doesn't exist, it should create a new file and give me a valid file descriptor. Instead it returns -1. If I run the code again however, I get fid = 3.
This is being run on ubuntu but it apparently works fine on windows and I can't figure out why.
-Mike

not sure if this helps, but note that if the folder doesn't exist, fopen with 'w' can't create the file and so returns -1.

You should check out the two-output-argument form of fopen in the doc here. This allows you to do stuff like
[fh, failmessage] = fopen( fname, 'wt' );
if fh == -1
error( 'Failed to open %s: %s', fname, failmessage );
end

Related

While running Compiled MatLab from console window, prompt returns immediately while app is still running

I have compiled my simple MatLab function so I can run it from a Windows console as a command line app. After I enter the command and its single argument, the prompt returns immediately even though the command is still running, as if running in the background.
Can someone tell me why this happens and how do I stop it? I'd like it to behave like a normal application and not return to the prompt until complete.
EDIT: Sorry I didn't post the code previously, I figured I was making a common mistake and would get a quick answer. Anyway, here it is.
It translates a .mat file to a .csv file and then runs another console command via "system" to perform a quick edit on the resulting .csv file. Several minutes of IO but not much else.
I've never compiled MatLab before so probably something simple, I hope.
function WriteMatToCSV( inFile, overWrite )
if ~exist(inFile, 'file')
fprintf('Error File not found: %s\n',inFile);
return;
end
overWriteExisting = 1;
if exist('overWrite','var')
overWriteExisting = overWrite;
end
% Change file extension
outFile = strrep( inFile, '.mat','.csv');
fprintf('In : %s\n',inFile);
fprintf('Out: %s\n',outFile);
% Overwrite if exists?
if exist(outFile, 'file')
if ~overWriteExisting
fprintf('Error File exists: %s\n',outFile);
return;
end
end
% Get variable name in the file
matObj = matfile(inFile);
info = whos(matObj);
name = info.name;
fprintf('Found variable: %s\n',name);
% Load the variable from the file
fprintf('Loading mat...\n');
load(inFile);
% Write the variable to .csv file
fprintf('Writing csv...\n');
export(eval(name),'File',outFile','Delimiter',',');
fprintf('Rewriting to remove MatLab bits...\n');
command = 'RewriteMatLabCSV';
command = [command ' ' outFile];
[status,cmdout] = system(command,'-echo');
fprintf(cmdout);
fprintf('Done\n');
end

creating a new blank .txt file using matlab

How can I create a blank .txt file? I use Matlab R2014a.
I want to check whether file of specified name exists and if it does not, I want to create one.
I do not like answering questions that just "ask" and provide no "I tried this...".
Nevertheless, there are many ways to accomplish what you are asking. This is one of them:
if exist('text.txt', 'file') == 0
disp('File does not exist, creating file.')
f = fopen( 'text.txt', 'w' );
fclose(f);
else
disp('File exists.');
end
to check if file exists, simply use the exist command:
exist( filename, 'file' )
To create an empty file, you can simply use fopen and fclose:
if ~exist(filename, 'file' )
fid = fopen(filename,'w');
fclose(fid);
end

Why I cannot open a txt file

I am really a new person in MATLAB and I need use it to finish my homework.
First, I try to open a txt file to get data.
So, I do like this:
folder='C:\Users\yshi20\Desktop\COSC6335\proj_1';
file='transactionDB.txt';
myData=fullfile(folder,file);
[Datafile, message] = fopen('transactionDB.txt', 'r');
But the datafile value always show -1 which means it failed to open.
So, I use this to check why I cannot open it:
if Datafile < 0
disp(message);
c = [];
else
Data = fread(Datafile, 5, 'uint8=>char')'
end
But the result says: No such file or directory.
But I checked many times, and I am sure the file name is correct and the location folder is correct, so, how to solve the problem?
You're using the wrong variable. You need to use myData in fopen.
[Datafile, message] = fopen(myData, 'r');
myData stores the complete path to your file whereas in your original code, you're using relative referencing which means that it's going to look for the file in the current working directory. A -1 code means that it can't find the file... and rightfully so given your error. It can't find the file in the current working directory. As such, make sure you change your fopen statement so that the correct path to your file is specified.

File Write Permission Issue in Matlab

I've been trying to write image files to the specified folder, but I always receive this error:
Unable to open file
"C:\Users\Dani\Desktop\code_version_1.0\myImages"
for writing. You may not have
write permission.
Is there a way to fix this? Thanks.
for i=1:numberOfFiles
filename=fileList{i};
img=imread(filename,'jpg');
image = imresize(img, [150,150]);
folder='C:\Users\Dani\Desktop\code_version_1.0\myImages';
if ~exist(folder,'dir')
mkdir(folder);
end
imwrite(image,folder,'jpg');
end
Your call to imwrite has an invalid second parameter. You gave it a folder when it is asking for a file path.
Here's a possible work-around:
outfile = fullfile(folder, 'output.jpg');
imwrite(image, outfile, 'jpg');
How about using the imwrite like this :
imwrite(image,'C:\Users\Dani\Desktop\code_version_1.0\myImages\image.jpg');
you can after append things as you like. check this link

Matlab: save string in a txt file

I have a long string with a lot of information, some empty rows and combined numbers and text in it. I tried to save it into txt file but it writes me a txt file with strange/unreadable characters:
Here is my code which does not work:
name_log = TPR_E01;
filename = strcat('New_',name_log);
save ( filename,'newCleanMarker')
Thank you!
save writes binary data by default. You can try the '-ascii' flag, or better still you can print the string to file
fid = fopen( ['New_', name_log], 'w' ); %// open file to writing
fprintf( fid, '%s', newCleanMarker ); %// print string to file
fclose( fid ); %// don't forget to close the file
Please see the following man pages
fopen - how to open a file in Matlab.
fullfile - a good practice to create file names and paths.
save - saving binary data, and the use of '-ascii' flag.