首頁 > 後端開發 > C++ > 主體

編寫一個C程式來列印所有檔案和資料夾

王林
發布: 2023-08-26 12:53:06
轉載
1401 人瀏覽過

編寫一個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
登入後複製

The logic that we use to display the files and folders in current directory, where the program saved is explained below −

dr = opendir(".");
if(dr!=NULL){
   printf("List of Files & Folders:-</p><p>");
   for(d=readdir(dr); d!=NULL; d=readdir(dr)){
      printf("%s</p><p>", d->d_name);
   }
   closedir(dr);
}
登入後複製

Example

Following is the C program for printing the files and folders in a directory −

#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:-</p><p>");
      for(d=readdir(dr); d!=NULL; d=readdir(dr)) {
         printf("%s</p><p>", d->d_name);
      }
      closedir(dr);
   }
   else
   printf("</p><p>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
登入後複製

以上是編寫一個C程式來列印所有檔案和資料夾的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
來源:tutorialspoint.com
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!