編寫一個 C 程式來列印所有檔案和資料夾。
檔案是記錄的集合(或)硬碟上永久儲存資料的地方。
透過使用 C 命令,我們可以以不同的方式訪問檔案。
檔案操作
以下是可以在 C 程式語言中對檔案執行的操作:
- 命名檔案
- 開啟檔案
- 從檔案讀取
- 寫入檔案
- 關閉檔案
語法
分別用於 **開啟和命名** 檔案的語法如下:
FILE *File pointer;
例如,FILE * fptr;
File pointer = fopen (“File name”, “mode”);
例如,fptr = fopen (“sample.txt”, “r”);
FILE *fp; fp = fopen (“sample.txt”, “w”);
**從檔案讀取** 的語法如下:
int fgetc( FILE * fp );// read a single character from a file
**寫入檔案** 的語法如下:
int fputc( int c, FILE *fp ); // write individual characters to a stream
我們用來顯示當前目錄中(程式儲存的位置)的檔案和資料夾的邏輯解釋如下:
dr = opendir("."); if(dr!=NULL){ printf("List of Files & Folders:-
"); for(d=readdir(dr); d!=NULL; d=readdir(dr)){ printf("%s
", d->d_name); } closedir(dr); }
示例
以下是用於列印目錄中檔案和資料夾的 C 程式:
#include<stdio.h> #include<conio.h> #include<dirent.h> int main() { struct dirent *d; DIR *dr; dr = opendir("."); if(dr!=NULL) { printf("List of Files & Folders:-
"); for(d=readdir(dr); d!=NULL; d=readdir(dr)) { printf("%s
", d->d_name); } closedir(dr); } else printf("
error while opening the directory!"); getch(); return 0; }
輸出
執行上述程式時,將產生以下輸出:
List of Files & Folders:- . .. accessing array.c accessing array.exe accessing array.o bhanu.txt C Programs convert 2 digit no into english word.c convert 2 digit no into english word.exe convert 2 digit no into english word.o DATA delete vowels in string.c delete vowels in string.exe delete vowels in string.o emp.txt EVEN ex.c ex.exe ex.o example pro.c example pro.exe example pro.o fibbinoci serie.c fibbinoci serie.exe fibbinoci serie.o file file example1.c file example1.exe file example1.o file example2.c file example2.exe file example2.o implicit conversion.c implicit conversion.exe implicit conversion.o leap year.c leap year.exe leap year.o little n big endian.c little n big endian.exe little n big endian.o work out examples
廣告