【问题标题】:Is stdin incompatible input stream when working with fopen();?使用 fopen(); 时标准输入是否不兼容?
【发布时间】:2013-11-12 05:02:12
【问题描述】:

我有一些演示代码希望用户输入文件名和模式。这本书暗示了可怕的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”。

【问题讨论】:

标签: c stream stdin fopen fgets


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2018-04-06
    • 1970-01-01
    • 1970-01-01
    • 2014-03-27
    • 1970-01-01
    • 1970-01-01
    • 2020-08-14
    • 2018-03-27
    • 1970-01-01
    相关资源
    最近更新 更多