C中的fgets()函数 [英] fgets() function in C

查看:47
本文介绍了C中的fgets()函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道每个人都告诉我使用fgets而不是因为缓冲区溢出而获取.但是,我对 fgets()中的第三个参数有些困惑.据我了解,fgets依赖于:

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 是将输入内容存储到的ptr.

char* str is the ptr to where my input will be stored.

num 是要读取的最大字符数.

num is the max number of character to be read.

但是什么是 FILE * stream ?如果我只是在提示用户输入字符串(如句子),我应该只输入" stdin "吗?

but what is FILE *stream? If I am just prompting the user to enter a string (like a sentence) should I just type "stdin" ?

我应该在靠近 main()的顶部键入 FILE * stdin 吗?

And should I type FILE *stdin at the top, near main()?

推荐答案

您是正确的. stream 是指向 FILE 结构的指针,就像从 fopen 返回的结构一样.已经为您的程序定义了 stdin stdout stderr ,因此您可以直接使用它们,而不必自己打开或声明它们.

You are correct. stream is a pointer to a FILE structure, like that returned from fopen. stdin, stdout, and stderr 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:

fgets(buffer, 10, stdin);

或从具有以下内容的特定文件中获取

Or from a specific file with:

FILE *f = fopen("filename.txt", "r");
fgets(buffer, 10, f);

这篇关于C中的fgets()函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆