如何使用VC++检查C:\驱动器中是否存在文件?

问题描述:

我想检查一个文件存在于C盘或不是..?任何人都可以告诉我如何?如何使用VC++检查C:驱动器中是否存在文件?

更新:

我的错误,我使用VC++ 2008

#include "stdafx.h" 
#include <stdio.h> 
int main(int argc, _TCHAR argv[]) 
{ 
    FILE * f = fopen("C:\\Program Files (x86)\\flower.jpeg"); 
    if (f == NULL) { 
     file_exists = FALSE: 
    } else { 
     file_exists = TRUE; 
     fclose(f); 
    } 
    return 0; 
} 

更新2

当试图从以下linked example剪切和粘贴代码:

#include "stdafx.h" 
#include <windows.h> 
#include "Shlwapi.h" 
int tmain(int argc, _TCHAR argv[]) 
{ 
    // Valid file path name (file is there). 
    TCHAR buffer_1[ ] = _T("C:\\TEST\\file.txt"); 
    TCHAR *lpStr1; 
    lpStr1 = buffer_1; 

    // Return value from "PathFileExists". 
    int retval; 

    // Search for the presence of a file with a true result. 
    retval = PathFileExists(lpStr1); 
    return 0; 
} 

我收到此错误:

files.obj : error LNK2019: unresolved external symbol [email protected] referenced in function _wmain 

给你提的C盘,我假设你可以使用Windows API如果是这样PathFileExists(LPCTSTR)会做你

+0

的#include “stdafx.h中” 的#include 的#include “Shlwapi.h” INT _tmain(INT的argc,_TCHAR * argv的[]){ \t //有效的文件的路径名(文件在那儿)。 TCHAR buffer_1 [] = _T(“C:\\ TEST \\ file.txt”); TCHAR * lpStr1; lpStr1 = buffer_1; \t //从“PathFileExists”返回值。 int retval; //搜索真实结果的文件。 retval = PathFileExists(lpStr1); \t return 0; } 我收到此错误 1> files.obj:错误LNK2019:解析外部符号__imp__PathFileExistsW @ 4在功能上引用_wmain 1> C:\ Users \用户USER1 \桌面\文件\调试\ files.exe: – pradeep 2010-05-25 10:31:16

+2

你链接到Shlwapi.lib?项目属性页>链接器>输入>附加依赖关系 – 2010-05-25 10:49:05

+0

是的,我确实将Shlwapi.lib添加到项目中 – pradeep 2010-05-25 10:57:08

当然 - 如果失败,只是尝试打开它,看看:

#include <stdio.h> 

int file_exists = 0; 
FILE * f = fopen("C:\\foo.dat", "rb"); 
if (f != NULL) 
{ 
    file_exists = 1; 
    fclose(f); 
} 

您不必打开它 - 只是用stat_stat

#include <sys/types.h> 
#include <sys/stat.h> 
#include <fcntl.h> 


struct _stat buffer; 
int   status; 
... 
status = _stat("mod1", &buffer); 
获取其状态

还有Windows API的功能,让你更多的控制

+1

MSVC++中是否存在? – ereOn 2010-05-25 09:38:16

这不是代码的问题,这是一个链接错误,因为它说。 你应该添加这个代码告诉链接器使用“shlwapi.lib”库。

#pragma comment(lib, "shlwapi.lib") 

在我的情况下,它解决了这个问题。 在Windows中,没有_stat的东西。但幸运的是,您不需要尝试打开它来了解其有效性,PathFileExists就是您使用的确切功能。