簡體   English   中英

如何使用VC ++檢查C:\\驅動器中是否存在文件?

[英]How to check whether a file exists in C:\ drive using 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

當嘗試從下面的鏈接示例中剪切和粘貼代碼時:

#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 

這不是代碼的問題,這就是它所說的鏈接錯誤。 您應該將此添加到告訴鏈接器使用“ shlwapi.lib”庫的代碼中。

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

就我而言,它可以解決問題。 在Windows中,沒有_stat的東西。 但幸運的是,您無需打開它即可檢查其有效性, PathFileExists是您需要的確切函數。

考慮到您提到的C驅動器,我假設您可以使用Windows API,如果可以,那么PathFileExists(LPCTSTR)可以幫助您

當然-嘗試打開它,看看它是否失敗:

#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函數可為您提供更多控制

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM