fprintf function

2 次查看(过去 30 天)
Jason
Jason 2011-2-3
I am trying to do a fprintf() to an object, here is my code:
object = fopen('file.txt');
string1 = '2';
string2 = 'GHz';
fprintf(object, 'The frequency is %s %s', string1, string2);
I have tried many variation of this but it keeps giving an error of too many inputs. String1 and string2 will change accordingly, that is why I have it like that. Please help me get this to output the right string. Thanks.
  2 个评论
Walter Roberson
Walter Roberson 2011-2-3
Is there are a reason you specifically say that you are trying to fprintf to an _object_ rather than saying that you are fprintf to a text file ? Do you mean to imply an object as in Object oriented programming? If your "object" is not the standard fopen(), perhaps an overridden method, then the fprintf() for that object class needs to be defined with varargin.
Jason
Jason 2011-2-3
I'm using the txt file just an example here. I do not have any problem opening whatever object I have. But yes this is more like Object oriented programming. I can write to the object with this code:
fprintf(object, 'The frequency is 2 GHz');

请先登录,再进行评论。

回答(1 个)

Rob Graessle
Rob Graessle 2011-2-3
Try opening your text file like this:
object = fopen('file.txt', 'w');
This will specify that the file object is to be used for writing to the file - see the 'permission' argument in the function documentation. The rest of your syntax looks good. Don't forget to close the file object when you're done writing to it:
fclose(object);
  3 个评论
Jason
Jason 2011-2-3
I don't think it has anything to do with how I open the file. For Example, this code work but not the one I had:
fprintf(object, 'The frequency is 2 GHZ');
Jan
Jan 2011-2-3
@Walter: 'w' works absolutely correct with text files. The 't' in the text mode influences the internal conversion of CHAR(10) to CHAR([13, 10]) and interpretation of CHAR(26) as "end of file". But even under Windows you can write a valid text file with FOPEN(File, 'w'). I'm sure, beginners are unnecessarily confused by the silent internal text mode conversions - and Linux simply does not care at all...

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Environment and Settings 的更多信息

标签

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by