windows 如何使用VC++检查C:\驱动器中是否存在文件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2903360/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to check whether a file exists in C:\ drive using VC++?
提问by pradeep
I want to check a file is present in C drive or not..? can any one tell me how ?
我想检查一个文件是否存在于 C 驱动器中..?谁能告诉我怎么做?
Update:
更新:
I got errors, I am using VC++ 2008
我遇到错误,我使用的是 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;
}
Update 2
更新 2
When trying to cut and paste code from the linked examplebelow:
尝试从以下链接示例中剪切和粘贴代码时:
#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;
}
I am getting this error:
我收到此错误:
files.obj : error LNK2019: unresolved external symbol __imp__PathFileExistsW@4 referenced in function _wmain
采纳答案by Dave Downs
Given you mention C drive, I'm assuming you can use the Windows API, if so PathFileExists(LPCTSTR)will do you
鉴于你提到 C 驱动器,我假设你可以使用 Windows API,如果是这样PathFileExists(LPCTSTR)会做你
回答by Allan Ruin
It's not the code's problem, this is a link error as it said. you should add this to your code which tell the linker to use "shlwapi.lib" library.
这不是代码的问题,正如它所说,这是一个链接错误。你应该把它添加到你的代码中,告诉链接器使用“shlwapi.lib”库。
#pragma comment( lib, "shlwapi.lib")
In my case, it solve the problem.
In windows ,there is not _stat thing. But luckily, you don't need to open it to check its validity, the PathFileExists
is the exact function you need.
就我而言,它解决了问题。在 Windows 中,没有 _stat 的东西。但幸运的是,您不需要打开它来检查其有效性,这PathFileExists
正是您需要的功能。
回答by user151019
回答by Paul R
Sure - just try opening it and see if it fails:
当然 - 只需尝试打开它,看看它是否失败:
#include <stdio.h>
int file_exists = 0;
FILE * f = fopen("C:\foo.dat", "rb");
if (f != NULL)
{
file_exists = 1;
fclose(f);
}