After creating a folder structure and .m file, I want to write to the file, but the fid keeps coming back as -1. What should i be doing that I'm not?

25 vues (au cours des 30 derniers jours)
% Here are the variable name string values:
% outputFileName = "Aaron.m"
% outputFilePath = "./folder/yayy/"
% currentSection is a string with a bunch of data
% ===================================
file = fullfile(outputFilePath, outputFileName);
mkdir(file);
[fid, msg] = fopen(file, 'w');
if fid == -1
error('Could not open file "%s" for writing.', file, msg);
end
% Write the content of the current section to the new .m file
fprintf(fid, '%s\n', currentSection);
% Close the file
fclose(fid);
  1 commentaire
Stephen23
Stephen23 le 9 Déc 2025 à 17:59
Modifié(e) : Stephen23 le 9 Déc 2025 à 17:59
"What should i be doing that I'm not?"
It is the other way around, you are doing something that you shouldn't: you create a folder with the value of file... which you then try to FOPEN. It is not possible to FOPEN a folder.

Connectez-vous pour commenter.

Réponse acceptée

dpb
dpb le 9 Déc 2025 à 17:55
Modifié(e) : dpb le 9 Déc 2025 à 19:05
file = fullfile(outputFilePath, outputFileName);
mkdir(file);
You created the directory with the fully qualified file name, not the folder...
% Here are the variable name string values:
% outputFileName = "Aaron.m"
% outputFilePath = "./folder/yayy/"
% currentSection is a string with a bunch of data
% ===================================
file = fullfile(outputFilePath, outputFileName);
if exist(outputFilePath)~=7 % see if already exists, if not create it but not multiple times
mkdir(outputFilePath);
end
[fid, msg] = fopen(file, 'w');
if fid == -1
error('Could not open file "%s" for writing.', file, msg);
end
% Write the content of the current section to the new .m file
fprintf(fid, '%s\n', currentSection);
% Close the file
fclose(fid);
  2 commentaires
Aaron
Aaron le 9 Déc 2025 à 19:22
That makes sense. Thanks for your help!
dpb
dpb le 9 Déc 2025 à 21:24
If that resovled your issue, go ahead and Accept an Answer to let folks know if nothing else...

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Data Import and Export dans Help Center et File Exchange

Produits

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by