Computer >> Máy Tính >  >> Lập trình >> lập trình C

Viết chương trình C để in tất cả các tệp và thư mục.

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

Bằng cách sử dụng các lệnh C, chúng ta có thể truy cập tệp theo nhiều cách khác nhau.

Thao tác trên tệp

Dưới đây là các thao tác có thể được thực hiện trên các tệp bằng ngôn ngữ lập trình C -

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

Cú pháp

Cú pháp cho mở đầu và đặt tên một tệp tương ứng được đưa ra bên dưới -

FILE *File pointer;

Ví dụ:FILE * fptr;

File pointer = fopen (“File name”, “mode”);

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

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

Cú pháp để đọc từ tệp như sau -

int fgetc( FILE * fp );// read a single character from a file

Cú pháp để ghi vào tệp như sau -

int fputc( int c, FILE *fp ); // write individual characters to a stream

Logic mà chúng tôi sử dụng để hiển thị các tệp và thư mục trong thư mục hiện tại, nơi chương trình được lưu được giải thích bên dưới -

dr = opendir(".");
if(dr!=NULL){
   printf("List of Files & Folders:-\n");
   for(d=readdir(dr); d!=NULL; d=readdir(dr)){
      printf("%s\n", d->d_name);
   }
   closedir(dr);
}

Ví dụ

Sau đây là chương trình C để in các tệp và thư mục trong một 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("List of Files & Folders:-\n");
      for(d=readdir(dr); d!=NULL; d=readdir(dr)) {
         printf("%s\n", d->d_name);
      }
      closedir(dr);
   }
   else
   printf("\nerror while opening the directory!");
   getch();
   return 0;
}

Đầu ra

Khi chương trình trên được thực thi, nó tạo ra kết quả sau -

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