使用 fopen 在脚本文件夹中创建一个新文件

Creating a new file in the script folder using fopen

我正在使用 MATLAB R2017a,我想在脚本所在的文件夹中创建一个新的二进制文件 运行。

我是 运行 matlab 管理员,否则它没有创建文件的权限。以下returns一个合法的fileID:

fileID = fopen('mat.bin','w');

但文件是在 c:\windows\system32.

中创建的

然后我尝试了以下操作以在脚本所在的文件夹中创建文件:

filePath=fullfile(mfilename('fullpath'), 'mat.bin');
fileID = fopen(filePath,'w');

但是我得到了一个无效的 fileId(等于 -1)。

变量 filePath 在运行时等于

'D:\Dropbox\Studies\CurrentSemester\ImageProcessing\Matlab Exercies\Chapter1\Ex4\mat.bin'

这对我来说似乎有效。

如果能帮我弄清楚该怎么做,我将不胜感激

问题是 mfilename returns 路径 包括文件名 (没有扩展名)。从文档中,

p = mfilename('fullpath') returns the full path and name of the file in which the call occurs, not including the filename extension.

要仅保留文件夹的路径,请使用 fileparts,其第一个输出正是这样。所以,在你的代码中,你应该使用

filePath = fullfile(fileparts(mfilename('fullpath')), 'mat.bin');