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



我一直在编写一个程序,需要读取一个.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个字符,并且还包含一个空格。为了从stdin读取该字符串,您可以使用以下内容:

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

最新更新