C - 如何提示用户输入文件名 [英] C - How to prompt user to enter filename

查看:52
本文介绍了C - 如何提示用户输入文件名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对 C 编程非常陌生.我正在编写一个程序,我想提示用户输入要打开以供阅读的文件的名称.在下面显示的代码中,如果它没有打开或者文件不存在,我想抛出一个错误,但是当我运行它时,我的代码会爆炸,我必须关闭程序(DOS)

Very new to C programming. I'm writing a program where I want to prompt the user to input the name of the file to be open for reading. On my code shown bellow I want to throw an error if it doesn't open or if the file doesn't exist, but when I run it, my code blows up and I have to close the program (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");
    }

//您可以通过创建 name.txt 文件来测试这一点.如果您需要其他信息,请告诉我.

// you can test this by creating a name.txt file. Please let me know if you need additional information.

推荐答案

好吧,你应该确保 fname 中有足够的空间来存储你的文件名,否则你几乎肯定会导致损坏和爆炸":-)

Well, you should make sure there's enough room in fname to store your file name, otherwise you'll almost certainly cause corruption and "blowing up" :-)

例如,以下代码段:

char fname[10];
gets (fname);

如果您输入的信息超出了 fname 的容量,将会有问题.那时,您进入了未定义的行为领域,任何事情都可能发生.

will be problematic if you enter more information than fname can hold. At that point, you're into undefined behaviour territory and anything can happen.

但是,由于 gets 无法限制用户输入的内容,你永远不应该使用它!

But, because gets provides no way to limit what the user enters, you should never use it!

可以在 这个答案.

它使用 fgets 因为这可以限制用户输入的内容.它还允许提示,如果出现问题提供错误指示,正确处理文件结尾,并删除任何过大行的剩余部分,使其不会影响下一个输入操作.

It uses fgets since that can limit what the user enters. It also allows for a prompt, provides an error indication if something goes wrong, handles end-of-file correctly, and removes the remainder of any too-large line so that it cannot affect the next input operation.

事实上,我会在这里复制它以使这个答案独立:

In fact, I'll copy it here to make this answer self-contained:

#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;
}

您可以按如下方式调用它,指定缓冲区和大小,并在返回时接收错误指示:

You can call it as follows, specifying the buffer and size, and receiving an error indication on return:

// 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;
}

这篇关于C - 如何提示用户输入文件名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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