C 中的 fgets() 函数
我知道每个人都告诉我使用 fgets 而不是 gets,因为缓冲区溢出。但是,我对 fgets() 中的第三个参数有点困惑。据我了解,fgets 依赖于:
char * fgets ( char * str, int num, FILE * stream );
char* str 是存储我的输入的 ptr。
num
是要读取的最大字符数。
但是FILE *stream
是什么?如果我只是提示用户输入一个字符串(例如一个句子),我应该只输入“stdin
”吗?
我应该在顶部靠近 main()
的地方输入 FILE *stdin
吗?
I know everybody has told me to use fgets and not gets because of buffer overflow. However, I am a bit confused about the third parameter in fgets()
. As I understand it, fgets is dependent on:
char * fgets ( char * str, int num, FILE * stream );
char* str
is the ptr to where my input will be stored.
num
is the max number of character to be read.
but what is FILE *stream
? If I am just prompting the user to enter a string (like a sentence) should I just type "stdin
" ?
And should I type FILE *stdin
at the top, near main()
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
你是对的。
stream
是指向FILE
结构的指针,类似于从fopen
返回的结构。stdin
、stdout
和stderr
已为您的程序定义,因此您可以直接使用它们,而不必自己打开或声明它们。例如,您可以使用以下命令从标准输入中读取:
或者使用以下命令从特定文件中读取:
You are correct.
stream
is a pointer to aFILE
structure, like that returned fromfopen
.stdin
,stdout
, andstderr
are already defined for your program, so you can use them directly instead of opening or declaring them on your own.For example, you can read from the standard input with:
Or from a specific file with:
是的,您应该只使用
stdin
。这是一个预定义的FILE *
,它从程序的标准输入中读取。如果您的文件顶部有#include
(fgets
需要它),那么它应该已经被定义。Yes, you should just use
stdin
. That is a predefinedFILE *
that reads from the standard input of your program. And it should already be defined if you have a#include <stdio.h>
at the top of your file (which you'll need forfgets
).一般来说,您可以通过两种方式与 C 语言中的文件进行通信。一种是使用低级操作系统相关系统调用,例如
open()
、read()
、write()
等与文件描述符一起使用。另一种是使用FILE
结构,该结构在 C 库函数中使用,例如fread()
、fwrite()
等,包括您上面提到的函数。正如 UNIX 哲学一样,一切皆文件。因此,即使标准输入 (
stdin
) 也被视为指向FILE
结构的指针。tl;dr 是的,您应该在调用
fgets()
时对FILE* 流
使用stdin
Broadly there are two ways you can communicate with files in C. One is using the low-level OS dependent system calls such as
open()
,read()
,write()
etc which work with file descriptors. Another one is usingFILE
structures which are used in C library functions likefread()
,fwrite()
etc including the one you mentioned above.As it is with the UNIX philosophy, everything is a file. So even the standard input (
stdin
) is treated as a pointer to aFILE
structure.tl;dr Yes, you should use
stdin
forFILE* stream
in your call tofgets()
FILE 是标准的 C 文件。是的,如果您想从标准输入读取, stdin 是正确的象征。
FILE is the standard C file. Yes, if you want to read from standard input, stdin is the correct symbol.