Search code examples
octavekeypress

Why is `fprintf/sprintf` not working on `keypressfcn`?


I was trying to type keyboard characters to a text file while my figure is open so I wrote down below code. Am I missing something ? (also tried with fprintf) Thank you very much

function myGUI()
    h.Mainfrm = figure("position", [200 200 200 200]);
    set(h.Mainfrm, "keypressfcn", @keypressCallback);
endfunction

function keypressCallback(hObject, eventdata)
    data  = eventdata;
    mystr = data.Character;
    fid   = fopen("mytext.txt");

    sprintf("%s" ,mystr)
    fclose(fid);
endfunction

Solution

  • You need to write into a file.

    fprintf( fid, '%s', mystr );
    

    Presumably you were using fprintf as fprintf( '%s', mystr ) which simply writes to the default output, which is your terminal.

    Furthermore, the file you are writing to needs have been opened as 'writable'! Or, in your case, since it seems you want to write character by character and append each character to your file, you need to open it with the 'append' flag:

    fid = fopen( 'mytext.txt', 'a');
    


    Btw, since all you're printing is a string, you don't need to specify '%s' at all, just print your string directly:

    fprintf( fid, mystr );
    

    If you want to do some sanity checking as well, capture the output of fprintf, which tells you how many characters have been saved into the file.

    Output = fprintf( fid, mystr );
    if Output == 0; fprintf( 'Nothing written to file\n' ); endif
    

    Also, note that fprintf does not terminate your strings with a newline. If you want a newline and your mystr does not have one at the end, then you need to specify one explicitly, i.e.:

    fprintf( fid, '%s\n', mystr );