Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Lập Trình C

Chương trình C in tất cả tệp và thư mục


Tệp là tập hợp bản ghi (hoặc nơi lưu trữ dữ liệu vĩnh viễn trên ổ cứng).

Bằng lệnh C, truy cập tệp nhiều cách.

Thao tác trên tệp

  • Đặt tên tệp
  • Mở tệp
  • Đọc từ tệp
  • Ghi vào tệp
  • Đóng tệp

Cú pháp

Cú pháp mở và đặt tên:

FILE *con_tro_tep;

Ví dụ: FILE *fptr;

con_tro_tep = fopen("Ten_tep", "che_do");

Ví dụ: fptr = fopen("sample.txt", "r");

FILE *fp; 
fp = fopen("sample.txt", "w");

Cú pháp đọc tệp:

int fgetc(FILE *fp); // doc mot ky tu

Cú pháp ghi tệp:

int fputc(int c, FILE *fp); // ghi ky tu

Logic hiển thị tệp/thư mục thư mục hiện tại:

dr = opendir("."); 
if(dr != NULL){ 
    printf("Danh sach File & Folder:-\n"); 
    for(d = readdir(dr); d != NULL; d = readdir(dr)){ 
        printf("%s\n", d->d_name); 
    } 
    closedir(dr); 
}

Ví dụ

Chương trình C in tệp/thư mục thư mục:

#include <stdio.h> 
#include <conio.h> 
#include <dirent.h> 
int main(){ 
    struct dirent *d; 
    DIR *dr; 
    dr = opendir("."); 
    if(dr != NULL){ 
        printf("Danh sach File & Folder:-\n"); 
        for(d = readdir(dr); d != NULL; d = readdir(dr)){ 
            printf("%s\n", d->d_name); 
        } 
        closedir(dr); 
    } else 
        printf("\nLoi mo thu muc!"); 
    getch(); 
    return 0; 
}

Đầu ra

Kết quả chạy chương trình:

Danh sach File & Folder:- 
. 
.. 
accessing array.c 
accessing array.exe 
... (cac file khac)