2

我有一些演示代码希望用户输入文件名和模式。这本书暗示了可怕的gets();输入函数,我拒绝使用,所以我尝试用 fgets() 获取我的输入。当我使用 fgets() 时,我将输入流指定为“stdin”,但是代码不起作用。但是,该代码将与 gets() 一起使用。我认为我实现 fgets() 的问题是“stdin”流类型。这就是为什么我的 fgets() 不能与这个程序一起工作的原因吗?如果是这样,我应该使用什么输入流类型?这是程序:

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    FILE *fp;
    char ch, filename[40], mode[4];

    while(1)
    {
        printf("\nEnter a filename: "); //This is where fgets/gets conflict is
        //fgets(filename, 30, stdin);     //I commented out the fgets()
        gets(filename);
        printf("\nEnter a mode (max 3 characters):");
        //fgets(mode, 4, stdin);                      //fgets again
        gets(mode);
        //Try to open the file
        if((fp = fopen(filename, mode)) != NULL)
        {
            printf("\nSuccessful opening %s in mode %s.\n",
                filename, mode);
            fclose(fp);
            puts("Enter x to exit, any other to continue.");
            if((ch = getc(stdin)) == 'x')
            {
                break;
            }else{
                continue;
            }
        }else
        {
            fprintf(stderr, "\nError opening file %s in mode %s.\n",
                filename, mode);
            puts("Enter x to exit, any other to try again.");
            if((ch = getc(stdin)) == 'x')
            {
                break;
            }else{
                continue;
            }
        }

}   
return 0;
}

提前谢谢大家。该程序来自 B. Jones 的“Teach Yourself C in 21 Days”。

4

1 回答 1

4

干得好不想用gets();这绝对是正确的方法。

打开文件的错误源于fgets()保留换行符而gets()不是保留换行符的事实。当您尝试使用换行符打开文件名时,找不到该文件。

于 2013-11-01T01:04:44.857 回答