⑴ 怎樣使用C語言列出某個目錄下的文件
C語言本身沒有提供象dir_list()這樣的函數來列出某個目錄下所有的文件。不過,利用C語言的幾個目錄函數,你可以自己編寫一個dir_list()函數。 首先,頭文件dos.h定義了一個find_t結構,它可以描述DOS下的文件信息,包括文件名、時間、日期、大小和屬性。其次,C編譯程序庫中有_dos_findfirst()和_dos_findnext()這樣兩個函數,利用它們可以找到某個目錄下符合查找要求的第一個或下一個文件。 dos_findfirst()函數有三個參數,第一個參數指明要查找的文件名,例如你可以用「*.*」指明要查找某個目錄下的所有文件。第二個參數指明要查找的文件屬性,例如你可以指明只查找隱含文件或子目錄。第三個參數是指向一個find_t變數的指針,查找到的文件的有關信息將存放到該變數中。 dos_findnext()函數在相應的目錄中繼續查找由_dos_findfirst()函數的第一個參數指明的文件。_dos_findnext()函數只有一個參數,它同樣是指向一個find_t變數的指針,查找到剛文件的有關信息同樣將存放到該變數中。 利用上述兩個函數和find_t結構,你就可以遍歷磁碟上的某個目錄,並列出該目錄下所有的文件,請看下例: #include <stdio.h> #include <direct.h> #include <dos.h> #include <malloc.h> #include <memory.h> #include <string.h> typedef struct find_t FILE_BLOCK void main(void); void main(void){FILE_BLOCK f-block; /* Define the find_t structure variable * / int ret_code; / * Define a variable to store the return codes * / / * Use the "*.*" file mask and the 0xFF attribute mask to list all files in the directory, including system files, hidden files, and subdirectory names. * / ret_code = _dos_findfirst(" *. * ", 0xFF, &f_block); /* The _dos_findfirst() function returns a 0 when it is successful and has found a valid filename in the directory. * / while (ret_code == 0){/* Print the file's name * / printf(" %-12s\n, f_block, name); / * Use the -dos_findnext() function to look
⑵ C語言怎麼讀取某一文件夾下的所有文件夾和文件
讀取的代碼方式如下:
intmain()
{
longfile;
struct_finddata_tfind;
_chdir("d:\");
if((file=_findfirst("*.*",&find))==-1L)
{
printf("空白! ");
exit(0);
}
printf("%s ",find.name);
while(_findnext(file,&find)==0)
{
printf("%s ",find.name);
}
_findclose(file);
return0;
}
⑶ c++獲取指定目錄下的文件名
可以使用searchenv函數來實現,參考代碼如下:
intmain(void)
{
charpathbuffer[_MAX_PATH];
charsearchfile[]="×.EXE";
charenvvar[]="PATH";
//:
_searchenv(searchfile,envvar,pathbuffer);//C4996
//Note:_searchenvisdeprecated;considerusing_searchenv_s
if(*pathbuffer!='