我正在编写一个程序,它计算每个C关键字包含在用户选择的ASCII文件中的次数 . 因此,我使用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 回答
我认为你的问题是
scanf
,而不是fopen
- 它处理带空格的文件名就好了 .scanf("%s")
只解析到第一个空格 . 如果没有看到更多的代码,很难提出修复 .Update: 由于您从stdin读取,您可以尝试此操作直到行终止符 .
Update 2 :修复了@chux报告的错误