Write a C program to print all files and folders.


File is a collection of records (or) a place on hard disk where the data is stored permanently.

By using C commands, we can access the files in different ways.

Operations on files

Given below are the operations which can be performed on files in the C programming language −

  • Naming the file
  • Opening the file
  • Reading from the file
  • Writing into the file
  • Closing the file

Syntax

The syntax for opening and naming a file respectively is given below −

FILE *File pointer;

For example, FILE * fptr;

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

For example, fptr = fopen (“sample.txt”, “r”);

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

The syntax for reading from file is as follows −

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

The syntax for writing into file is as follows −

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:-
");    for(d=readdir(dr); d!=NULL; d=readdir(dr)){       printf("%s
", 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:-
");       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; }

Output

When the above program is executed, it produces the following output −

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

Updated on: 25-Mar-2021

991 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements