文件名包含空格无法用fopen打开

时间:2017-05-15 01:42:58

标签: c file fopen

我正在编写一个程序,用于计算用户选择的ASCII文件中每个C关键字包含多少次。因此,我使用scanf保存用户选择为文件名的名称,并使用fopen检查具有该名称的文件是否与C程序位于同一目录中。问题在于,如果用户选择的文件名包含空格,则fopen会发出错误,因为它无法找到这样的文件。所以这就是问题,如何用fopen打开一个包含空格的文件?这是我用于程序的代码

selectfilename(filein,1) ;
if (fopen(filein,"r") == NULL){
    perror("Error ") ;
    return (1) ;
}

void selectfilename(char *cp, int num){
    if (num == 1) printf("Please select the name of the file to be opened  including the extension : ") ;               
    else printf("Please select the name of the file to save the statistics including the extension : ") ;               
    scanf("%s",cp++) ;
}

1 个答案:

答案 0 :(得分:3)

我认为您的问题出在fopen上,而不是scanf("%s") - 它处理带空格的文件名就好了。

char buf[256]; int rv = scanf ("%255[^\n]", buf); // 255 is max chars to read if (rv == 0 || rv == EOF) buf[0] = 0; printf ("[%s]\n", buf); 只解析到第一个空格。在没有看到更多代码的情况下提出修复很难。

<强>更新 由于你从stdin读取,你可以尝试这个读取直到行终止符。

.content {
font-size: 0;
}

.row {
  text-align:center;
}
.square {
    height: 10rem;
    width: 118px;
    display: inline-block;
    margin: 1rem 1.5%;
    background: #000000;
}

   #square-5 {
    margin: 0 auto;
}

更新2 :修复了@chux

报告的错误
相关问题