gpt4 book ai didi

c - 如何在C中的fopen中使用字符串数组作为txt文件名

转载 作者:行者123 更新时间:2023-11-30 19:12:45 25 4
gpt4 key购买 nike

我一直在开发一个程序,我需要读取一个 .txt 文件。但是,要打开的文件的名称必须由用户指定:

#include stdio.h    

int main(void) {
char FN[30];

FILE *Fptr;

printf("%s","Enter the full path of the file you wish to open.\n");
scanf("%s",FN);
if ((Fptr=fopen(FN,"r+"))==NULL) {
printf("%s","File could not be opened.\n");
} else {
printf("%s","File opened successfully.\n");
}
}

我反复收到消息“无法打开文件”。我认为问题一定出在我用作文件名的数组中,因为当我尝试时:

if ((Fptr=fopen("/Volumes/NO NAME/IntroProgramming/Version-0/test.txt","r+"))==NULL) 

而不是:

if ((Fptr=fopen(FN,"r+"))==NULL)

程序运行得很好。

最佳答案

在您提供的示例中,文件名(应使用“”括起来)的长度超过了为 FN 变量分配的 30 个字符,并且还包含空格。为了从标准输入读取该字符串,您可以使用如下内容:

char FN[129];

if ( scanf("%128[^\n] ", FN) != 1 ) {
fprintf(stderr,"No string was read from stdin.\n");
}

关于c - 如何在C中的fopen中使用字符串数组作为txt文件名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36530551/

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