【问题标题】:How to use fopen to open a file that has a name specified by the user?如何使用 fopen 打开具有用户指定名称的文件?
【发布时间】:2016-07-03 21:03:24
【问题描述】:

现在我有这个:

printf("Please enter your file name with\nthe file type then hit enter followed by ctrl+z\nthen enter 1 final time\n");
char tempChar;
int counter = 0;
char fileName[1000];
int boolean1 = 0;
    while(boolean1 == 0)
    {
        tempChar = getchar();
        if(tempChar == EOF)
            break;
        else
            fileName[counter] = tempChar;
        counter++;
}

fileName 是文件名。这个命令很有效,它给了我一个他们想要的名字的 char 数组。但是,我不知道如何将其传递给fopen()。我已经尝试过fopen(fileName, "r");,并且我已经尝试过在文件名上加上引号。我也尝试过 fopen("%c",&fileName,"r"); 我相信这是因为 1000 长度字符数组中出现了额外的垃圾,但我该如何解决这个问题?

【问题讨论】:

  • 我做了 4 个空格的事情来指定什么是代码,什么不是,但如果它看起来像一团糟,它就不起作用了。
  • 从用户处读取最后一个字符后,在字符串中添加一个尾随 null。或者使用库函数来读取输入而不是自己编写:)
  • 您想了解 C 如何模拟数据类型“字符串”,因为它在这种语言中通常不存在,尤其是在 0-terminated char-arrays 上。
  • 或者只是阅读 C 入门。
  • 使用此代码, 将存储在文件名的末尾。也许您想将 EOF 更改为 '\n' 以便在用户按 Enter 时停止。

标签: c arrays fopen


【解决方案1】:

C 中的字符串需要以空字符 ('\0') 终止,而您没有这样做。

【讨论】:

    【解决方案2】:

    我认为,您不需要 明确地获取和 EOF,只需检查换行符 ('\n'),然后 null 终止数组并将其传递给 fopen() .

    类似

    while(1)
        {
            tempChar = getchar();
            if(tempChar == '\n'){
                fileName[counter] = '\0';  //null-terminate
                break;
                }
            else
                fileName[counter] = tempChar;
            counter++;
    }
    

    会做的。

    也就是说,FWIW,

    • getchar() 返回一个int,它可能不适合char(例如,EOF),所以将tempChar 更改为int 类型,这样会更好。
    • 总是初始化你的局部变量,比如char fileName[1000] = {0};

    另一种更简单的方法是使用fgets() 立即读取用户的输入,处理(删除终止的空值)并将其传递给fopen()

    【讨论】:

    • 所以我将 if 语句切换为 if (tempchar == '\n'){artname[counter] = '\0';休息; } 并且代码仍然无法执行。在我发表评论之前编辑你改变了你的这是非常具体的帮助谢谢你我真的很感激!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-15
    • 1970-01-01
    相关资源
    最近更新 更多