我想检查一个文件是否存在于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
当试图从下面的链接示例中剪切和粘贴代码时:
#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 __imp__PathFileExistsW@4 referenced in function _wmain
鉴于你提到的C驱动器,我假设你可以使用Windows API,如果这样PathFileExists(LPCTSTR)会做你
这不是代码的问题,这是一个链接错误,因为它说。 你应该添加这个代码告诉链接器使用“shlwapi.lib”库。
#pragma comment( lib, "shlwapi.lib")
在我的情况下,它解决了这个问题。 在Windows中,没有_stat的东西。 但幸运的是,您不需要尝试打开它来验证其有效性, PathFileExists
就是您使用的确切功能。
当然 – 试着打开它,看看是否失败:
#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的功能,让你更多的控制