C语言实现读取目录和文件

您所在的位置:网站首页 c语言文件路径读取 C语言实现读取目录和文件

C语言实现读取目录和文件

2022-09-27 13:36| 来源: 网络整理| 查看: 265

通过此程序熟悉以下知识点:

  1. perror ( ):用 来 将 上 一 个 函 数 发 生 错 误 的 原 因 输 出 到   标 准 错误 (stderr) 。参数 s 所指的字符串会先打印出,后面再加上错   误原因字符串。此错误原因依照全局变量errno 的值来决定要输出的字符串。   2. dirent是一个结构体:

    struct dirent      {          long d_ino; /* inode number 索引节点号 */          off_t d_off; /* offset to this dirent 在目录文件中的偏移 */          unsigned short d_reclen; /* length of this d_name 文件名长 */          unsigned char d_type; /* the type of d_name 文件类型 */          char d_name [NAME_MAX+1]; /* file name (null-terminated) 文件名,最长255字符 */      }    3. exit 用于在程序运行的过程中随时结束程序, 其参数是返回给 OS 的 。也可以这么讲: exit 函数是退出应用程序 , 并将应用程序的一个状态返回给 OS ,这个状态标识了应用程序的一些运行信息。

main 函数结束时也会隐式地调用 exit 函数, exit 函数运行时首先会执行由 atexit() 函数登记的函数,然后会做一些自身的清理工作,同时刷新所有输出流、关闭所有打开的流并且关闭通过标准 I/O 函数 tmpfile() 创建的临时文件。

exit 是系统调用级别的, 它表示了一个进程的结束, 它将删除进程使用的内存空间,同时把错误信息返回父进程。通常情况: exit(0) 表示程序正常 , exit(1) 和 exit(-1) 表示程序异常退出, exit(2) 表示系统找不到指定的文件。

 

下面的程序实现打开一个目录下的文件并向文件中写入内容(固定程式):

 

/* Author:longmenyu */  #include  #include       #include   int main(void) {     DIR *dir;     struct dirent *ptr;     FILE *file;     char c;      if ((dir=opendir("/home/eagle/test")) == NULL)     {         perror("Open dir error...");         exit(1);            }     while ((ptr=readdir(dir)) != NULL)     {         printf("d_name:%s\n",ptr->d_name);     }     if ((file=fopen("./writefile.c","w")) == NULL)     {         perror("Open file failed...");         exit(1);     }     while ((c=getchar())!='q')     {         fputc(c,file);     }     fclose(file);     closedir(dir); } 

注意:

1. error()函数必须包含头文件——#include ,否则gcc将显示以下警告信息:

    warning: incompatible implicit declaration of built-in function

2.由于历史原因,程序末尾需空出一行,否则将有以下警告:

        warning: no newline at end of file


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3