首页 > 后端开发 > 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学习者快速成长!