如何验证文件名中的用户输入 [英] how to validate user input in file name

查看:70
本文介绍了如何验证文件名中的用户输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想编写该文件名输入,允许用户3输入有效的文件名。如果在3次机会后没有输入有效的文件名,则终止程序。

else打印成功消息

I want to program that file name input that allow the user 3 chances to enter a valid file name. If a valid file name is not entered after 3 chances, terminate the program.
else print successful message

推荐答案

这通常取决于什么你的意思是''有效的文件名'',例如它的道路应该是正式的吗?它应该是现有文件吗?它应该是一个新文件吗? (我们应该买一把新吉他吗?)。

根据你的需要,你必须建立你的验证功能(它可能很简单,例如只是试图打开文件)。一旦你有了验证功能,你只需要跟踪失败的尝试并关闭程序,如果这个数字变为3.



[更新]

我会用

That usually depend on what you mean with ''valid filename'', e.g. Should its path be formally correct? Should it be an existing file? Should it be a new file? ("Should we buy a new guitar?").
Depending on your needs you have to build your validation function (it might be very simple, e.g. just trying to open the file). Once you have the validation function you have only to keep track of failed attempts and close the program if this number becomes 3.

[Update]
I would use
int i;
FILE fp = NULL;
for (i=0; i<3; i++)
{
  printf("\n\nEnter filename :" );
  gets( fname );
  fp = fopen (fname, "r");
  if (fp)
    break;
  printf("Cannot open %s for reading \n", fname );
}
if ( ! fp ) return -1; // exit the program here
// fp is OK here, you may continue...



[/更新]


[/Update]


您是否要求代码检查文件系统上是否存在有效文件名或特定文件名?



对于后者:



Are you asking for code to check for a valid filename or that a particular filename exists already on the file system?

For the latter:

int fileExists(TCHAR * file)
{
   WIN32_FIND_DATA FindFileData;
   HANDLE handle = FindFirstFile(file, &FindFileData) ;
   int found = handle != INVALID_HANDLE_VALUE;
   if(found) 
   {
       FindClose(&handle);
   }
   return found;
}





此代码查看文件是否存在而不打开它。



This code looks to see if a file exists without opening it.


这篇关于如何验证文件名中的用户输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆