简体   繁体   English

为什么在MATLAB中使用fprintf会出错?

[英]Why am I getting an error for using fprintf in MATLAB?

This is my code. 这是我的代码。

function typeHere_KeyPressFcn(hObject, eventdata, handles)
% hObject    handle to typeHere (see GCBO)
% eventdata  structure with the following fields(seeMATLAB.UI.CONTROL.UICONTROL)
% Key: name of the key that was pressed, in lower case
% Character: character interpretation of the key(s) that was pressed
% Modifier: name(s) of the modifier key(s) (i.e., control, shift) pressed
% handles    structure with handles and user data (see GUIDATA)
    persistent ticStartTime;
    global currentUser;
    ticStartTime = tic;
    out = sprintf('%s',eventdata.Key);
    %disp(out)
    if isempty(ticStartTime)
        time=toc; % use last the tic from the key_pressFcn
    else
        time = toc(ticStartTime); % use tic that was called within this callback
    end
    path = ['Database\' currentUser '\keyCapture_gui1\keyTiming0.txt'];
    fd = fopen(path,'a+'); %write in a file
    fprintf(fd,'%s\n%s',out,time);
    fclose(fd);

This code is accepting each keystroke from a keyboard and simultaneously storing it in a text file but when I run the code, sometimes it works, sometimes it gives the following error message. 该代码接受键盘上的每个击键,并将其同时存储在文本文件中,但是当我运行该代码时,有时它会起作用,有时会给出以下错误消息。

Error using fprintf
Invalid file identifier. Use fopen to generate a valid file identifier.

Error in gui1>typeHere_KeyPressFcn (line 162)
    fprintf(fd,'%s\n%s',out,time);

Error in gui_mainfcn (line 95)
        feval(varargin{:});

Error in gui1 (line 42)
    gui_mainfcn(gui_State, varargin{:});

Error in
matlab.graphics.internal.figfile.FigFile/read>@(hObject,eventdata)gui1('typeHere_KeyPressFcn',hObject,eventdata,guidata(hObject))
Error while evaluating UIControl KeyPressFcn

Please help me out, I'm stuck! 请帮帮我,我卡住了!

What you are doing is to open a file on !EVERY! 您正在做的是打开!EVERY!上的文件。 keypress, appeding some text then closing it. 按键,敲击一些文本然后将其关闭。

Therefore, when you press a key you shall open a file and close it !BEFORE! 因此,当您按下一个键时,您将打开一个文件并关闭它! the next keypress arrives. 下一次按键到达。 Based on hard drive speed (HDD-SSD) it is absolutely possible that typing fires keypress events faster that your file-handling mechanism can handle. 基于硬盘驱动器的速度(HDD-SSD),绝对有可能键入会触发文件处理机制可以处理的按键事件。 In this case you will get a not valid file identifier as the file still in use (by you). 在这种情况下,您将获得无效的文件标识符,因为该文件仍在使用中(由您自己)。

What I could suggest is to open and close the file only once. 我可以建议打开和关闭文件一次。

You could store on a buttonpress, or on focus lost of the control where the user typing in. 您可以将其存储在按钮上,也可以存储在用户输入控件丢失的焦点上。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM