Avinandan Nandi
Avinandan Nandi

Reputation: 11

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!

Upvotes: 0

Views: 145

Answers (1)

DVarga
DVarga

Reputation: 21799

What you are doing is to open a file on !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. 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.

Upvotes: 0

Related Questions