fgets() function in C

后端 未结 4 1591
北海茫月
北海茫月 2020-12-31 06:17

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 unde

相关标签:
4条回答
  • 2020-12-31 06:43

    Yes, you should just use stdin. That is a predefined FILE * 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 for fgets).

    0 讨论(0)
  • 2020-12-31 06:59

    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);
    
    0 讨论(0)
  • 2020-12-31 07:02

    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 using FILE structures which are used in C library functions like fread(), 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 a FILE structure.

    tl;dr Yes, you should use stdin for FILE* stream in your call to fgets()

    0 讨论(0)
  • 2020-12-31 07:06

    FILE is the standard C file. Yes, if you want to read from standard input, stdin is the correct symbol.

    0 讨论(0)
提交回复
热议问题