Discover MakerZone

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

Learn more

Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today

New to MATLAB?

difference between sprintf and fprintf

Asked by fantic

fantic (view profile)

on 16 Sep 2011

I've read many answers regarding this question, but I still do not get the gist of it. So what if sprintf writes to a screen, while fprintf writes to a file? How does it matter/make a difference?

Please try to explain in layman's term because I'm only a beginner.




fantic (view profile)


No products are associated with this question.

1 Answer

Answer by Walter Roberson

Walter Roberson (view profile)

on 16 Sep 2011

Yes, both of them format data using the same formatting rules. sprintf() returns the formatted data as a string, which the user can store or further manipulate or display as appropriate. fprintf() writes the formatted data to whichever file or device (such as a serial port) it is connected to.

You may have also seen reference to fwrite(). fprintf(fid,...) is (for these purposes) the same as fwrite(fid,sprintf(...)) but fprintf() does not (theoretically) need to build the entire string before writing it out to the connected device. fprintf() could be thought of as a convenience for the combination of sprintf and fwrite, but it is a convenience that is used often enough to be worth having.

(There is a small difference between fprintf() and sprintf() if the destination is a serial port, but it is unimportant at the moment.)


Walter Roberson

Walter Roberson (view profile)

Contact us