我理解"隐式声明"通常意味着在调用函数之前必须将函数置于程序的顶部,或者我需要声明原型.
但是,gets
应该在stdio.h
文件中(我已经包含在内).
有没有什么办法解决这一问题?
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
char ch, file_name[25];
FILE *fp;
printf("Enter the name of file you wish to see\n");
gets(file_name);
fp = fopen(file_name,"r"); // read mode
if( fp == NULL )
{
perror("Error while opening the file.\n");
exit(EXIT_FAILURE);
}
}
Run Code Online (Sandbox Code Playgroud)
chq*_*lie 13
gets()
从C11标准中删除.不要使用它.这是一个简单的替代方案:
#include <stdio.h>
#include <string.h>
char buf[1024]; // or whatever size fits your needs.
if (fgets(buf, sizeof buf, stdin)) {
buf[strcspn(buf, "\n")] = '\0';
// handle the input as you would have from gets
} else {
// handle end of file
}
Run Code Online (Sandbox Code Playgroud)
您可以将此代码包装在函数中,并将其用作以下代码的替代gets
:
char *mygets(char *buf, size_t size) {
if (buf != NULL && size > 0) {
if (fgets(buf, size, stdin)) {
buf[strcspn(buf, "\n")] = '\0';
return buf;
}
*buf = '\0'; /* clear buffer at end of file */
}
return NULL;
}
Run Code Online (Sandbox Code Playgroud)
并在您的代码中使用它:
int main(void) {
char file_name[25];
FILE *fp;
printf("Enter the name of file you wish to see\n");
mygets(file_name, sizeof file_name);
fp = fopen(file_name, "r"); // read mode
if (fp == NULL) {
perror("Error while opening the file.\n");
exit(EXIT_FAILURE);
}
}
Run Code Online (Sandbox Code Playgroud)