gpt4 book ai didi

c - 我如何要求用户提供文件名以用作输入文件?

转载 作者:太空宇宙 更新时间:2023-11-04 03:51:51 24 4
gpt4 key购买 nike

这是我的第一篇文章,所以我希望我做的一切都是正确的。我已经搜索过谷歌和这个网站,但找不到我要找的答案。

我正在尝试提示用户输入文件名并将该文件名输入到 fopen 中。当我尝试运行并输入现有文本文件(扩展名为 .txt)时,我仍然遇到 filenotfound 错误消息。

到目前为止,这是我的代码(只是试图立即打开文件):

#include <stdio.h>
main(){
int c;
FILE *file;
char filename[99];
fgets(filename, 99, stdin);

file = fopen(filename, "r");

if (file) {
while ((c = getc(file)) != EOF)
putchar(c);
fclose(file);
} else{
puts("FILE NOT FOUND");
}
return 0;
}

我猜这与我将它放入一个字符数组有关?有什么方法可以用它们制作字符串还是别的什么?

最佳答案

fgets() 保留换行符 (\n)。您需要将其删除。一种方法是更改​​:

fgets(filename, 99, stdin);

fgets(filename, 99, stdin);
char *p = strchr(filename, '\n'); // p will point to the newline in filename
if(p) *p = 0; // if p is not null, terminate filename at p

关于c - 我如何要求用户提供文件名以用作输入文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20083704/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com