判断文件是否存在
2023-05-19
53
0
函数如下:
inline bool is_file_exist(const std::string& filepath)
{
struct _stat buffer;
return _stat(filepath.c_str(), &buffer) == 0;
}
_stat
, _wstat
函数用于获取文件的状态信息。
函数返加0表进成功,为-1表示失败即文件不存在。
参考链接:https://learn.microsoft.com/zh-cn/previous-versions/14h5k7ff(v=vs.110)
// crt_stat.c
// This program uses the _stat function to
// report information about the file named crt_stat.c.
#include <time.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include <errno.h>
int main( void )
{
struct _stat buf;
int result;
char timebuf[26];
char* filename = "crt_stat.c";
errno_t err;
// Get data associated with "crt_stat.c":
result = _stat( filename, &buf );
// Check if statistics are valid:
if( result != 0 )
{
perror( "Problem getting information" );
switch (errno)
{
case ENOENT:
printf("File %s not found.\n", filename);
break;
case EINVAL:
printf("Invalid parameter to _stat.\n");
break;
default:
/* Should never be reached. */
printf("Unexpected error in _stat.\n");
}
}
else
{
// Output some of the statistics:
printf( "File size : %ld\n", buf.st_size );
printf( "Drive : %c:\n", buf.st_dev + 'A' );
err = ctime_s(timebuf, 26, &buf.st_mtime);
if (err)
{
printf("Invalid arguments to ctime_s.");
exit(1);
}
printf( "Time modified : %s", timebuf );
}
}