C 编程的新手。我正在编写一个程序,我想提示用户输入要打开以供阅读的文件的名称。在我下面显示的代码中,如果它没有打开或文件不存在,我想抛出一个错误,但是当我运行它时,我的代码爆炸了,我必须关闭程序(DOS)
/*ask user for the name of the file*/
printf("enter file name: ");
gets(fname);
//Opens the file from where the text will be read.
fp=fopen(fname, "r");
//Checks if the file us unable to be opened, then it shows the error message
if (fp == NULL)
{
printf("\nError, Unable to open the file for reading\n");
}
Run Code Online (Sandbox Code Playgroud)
// 您可以通过创建 name.txt 文件来测试这一点。如果您需要其他信息,请告诉我。
好吧,你应该确保有足够的空间fname
来存储你的文件名,否则你几乎肯定会导致损坏和“爆炸”:-)
例如,以下代码段:
char fname[10];
gets (fname);
Run Code Online (Sandbox Code Playgroud)
如果您输入的信息多于fname
可以容纳的信息,则会出现问题。在这一点上,您进入了未定义的行为领域,任何事情都可能发生。
但是,因为gets
没有办法限制用户输入的内容,所以你永远不应该使用它!
可以在此答案中找到适当的受保护的用户输入方法。
它使用fgets
因为这可以限制用户输入的内容。它还允许提示,在出现问题时提供错误指示,正确处理文件结尾,并删除任何过大行的其余部分,以便它不会影响下一个输入操作。
事实上,我会在这里复制它以使这个答案独立:
#include <stdio.h>
#include <string.h>
#define OK 0
#define NO_INPUT 1
#define TOO_LONG 2
static int getLine (char *prmpt, char *buff, size_t sz) {
int ch, extra;
// Get line with buffer overrun protection.
if (prmpt != NULL) {
printf ("%s", prmpt);
fflush (stdout);
}
if (fgets (buff, sz, stdin) == NULL)
return NO_INPUT;
// If it was too long, there'll be no newline. In that case, we flush
// to end of line so that excess doesn't affect the next call.
if (buff[strlen(buff)-1] != '\n') {
extra = 0;
while (((ch = getchar()) != '\n') && (ch != EOF))
extra = 1;
return (extra == 1) ? TOO_LONG : OK;
}
// Otherwise remove newline and give string back to caller.
buff[strlen(buff)-1] = '\0';
return OK;
}
Run Code Online (Sandbox Code Playgroud)
您可以按如下方式调用它,指定缓冲区和大小,并在返回时接收错误指示:
// Test program for getLine().
int main (void) {
int rc;
char buff[10];
rc = getLine ("Enter string> ", buff, sizeof(buff));
if (rc == NO_INPUT) {
// Extra NL since my system doesn't output that on EOF.
printf ("\nNo input\n");
return 1;
}
if (rc == TOO_LONG) {
printf ("Input too long [%s]\n", buff);
return 1;
}
printf ("OK [%s]\n", buff);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
26779 次 |
最近记录: |