我尝试使用以下代码将字符传递到字符串中并打开 .txt 文件,以便我可以读取它的内容。我不知道为什么以及如何利用这个 fopen 来实际读取 test.txt
int main(){
char input[60];
char a;
FILE *file;
printf("Hello!\n");
enter code here
printf("Pelase input a file name in .txt format: \n");
gets(input);
printf("%s",input);
printf("\n");
**file = fopen("%c,input","rt");**
//file = fopen("%s",input) <-- 不起作用
//file = fopen("%s",input,rt) <-- 错误
if (file){
while((a=fgetc(file))!=EOF){
printf("%c",a);
}
fclose(file);
}
}
最佳答案
如果您想将“.txt”
添加到用户输入的任何内容中,然后打开该文件,您可以使用:
gets (input);
strcat (input, ".txt");
file = fopen (input, "r");
请注意,我不提倡使用gets
,或者在不首先检查大小的情况下盲目追加到缓冲区,但这是实现您的目标所需的最小必要更改想。请参阅下文,了解为什么这两件事不是一个好主意。
当前代码的其他问题:
fgetc()
的返回值是,因此a
的类型应该是int
。gets()
函数本质上是不安全的,以至于它已从标准中删除。使用fgets()
或查找 safe user input function .永远不要盲目地追加到缓冲区。就像使用
gets()
和某些scanf()
格式字符串一样,它会允许代码中出现缓冲区溢出。
关于c - 如何使用 char 将字符串传递给 fopen C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25637346/