是否可以使用fgets或gets_s正确读取空字符? [英] Is it possible to read null characters correctly using fgets or gets_s?
问题描述
假设我想从stdin
中读取内容,并让用户输入包含空字符的字符串.使用像fgets
或gets_s
这样的字符串输入函数可以做到这一点吗?还是我必须使用例如fgetc
或fread
?
Suppose I want to read from stdin
, and let the user input strings that contain null characters. Is this possible with string-input functions like fgets
or gets_s
? Or do I have to use e.g. fgetc
or fread
?
有人此处想要这样做.
推荐答案
是否可以使用fgets或gets_s正确读取空字符?
Is it possible to read null characters correctly using fgets or gets_s?
正如其他一些答案所示,答案显然是是的-几乎没有".同样,可以使用螺丝刀锤打钉子.同样,可以用C编写(相当于)BASIC或FORTRAN代码.
As some of the other answers show, the answer is apparently "Yes -- just barely." Similarly, it is possible to hammer in nails using a screwdriver. Similarly, it is possible to write (what amounts to) BASIC or FORTRAN code in C.
但是这些都不是一个好主意.使用正确的工具完成工作.如果要打钉子,请使用锤子.如果要编写BASIC或FORTRAN,请使用BASIC解释器或FORTRAN编译器.而且,如果您想读取可能包含空字符的二进制数据,请使用fread
(或者可能是getc
).不要使用fgets
,因为它的接口从未设计用于此任务.
But none of these things is remotely a good idea. Use the right tool for the job. If you want to drive nails, use a hammer. If you want to write BASIC or FORTRAN, use a BASIC interpreter or a FORTRAN compiler. And if you want to read binary data that might contain null characters, use fread
(or maybe getc
). Don't use fgets
, because its interface was never designed for this task.
这篇关于是否可以使用fgets或gets_s正确读取空字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!