从0到1用代码入门C语言(五)

134 阅读2分钟

本文已参与 ⌈新人创作礼⌋ 活动,一起开启掘金创作之路。
本文已参与 ⌈新人创作礼⌋ 活动,一起开启掘金创作之路。 接四,补充相关内容

十一、文件

fwrite函数写到用户空间缓冲区,并未同步到文件中,所以修改后要将内存与文件同步可以用fflush(FILE *fp)函数同步。

从文件中读取数据:

fread(&数据存放地址,固定值1,读取数据的长度,文件指针);

文件定位函数:

//ftell,返回当前文件位置指针的值,这个值是当前位置相对于文件开始位置的字节数
long ftell(FILE *fp);
//rewind,将位置指针移动到文件开头
void rewind(FILE *fp);
//fseek,将位置指针移动到任意位置
int fseek(FILE *fp,lonf offset,int origin);

文件缓冲区,调用fprintf、fwrite等函数往文件写入数据时,数据不会立即写入磁盘文件,而是先写入缓冲区,若想把缓冲区数据立即写入文件,可以调用fflush库函数

int fflush(FILE *fp);

十二、目录与时间操作 C通过getcwd函数可以获取当前的工作目录,举例说明:

char strpwd[301];
memset(strpwd,0,sizeof(strpwd));
getcwd(strpwd,300);
printf("当前目录是:%s",strpwd);

切换工作目录:

int chdir(const char *path);

C语言用mkdir/rmdir函数来创建/删除目录:

int mkdir(const char *pathname,mode_t mode);
int rmdir(const char *pathname);

获取文件列表:

#include <dirent.h>

打开目录的函数声明:

DIR *opendir(const char *pathname)

读取目录的函数声明:

struct dirent *readdir(DIR *dirp);

关闭目录的函数closedir的声明:

int closedir(DIR *dirp);
#include <stdio.h>
#include <dirent.h>
int ReadDir(const char *strpathname);
int main(int argc,char *argv[])
{
  if (argc != 2)  { printf("请指定目录名。\n"); return -1; }
  ReadDir(argv[1]);
}
int ReadDir(const char *strpathname)
{
  DIR *dir; 
  char strchdpath[256];   
  if ( (dir=opendir(strpathname)) == 0 ) return -1; 
  struct dirent *stdinfo; 
  while (1)
  {
    if ((stdinfo=readdir(dir)) == 0break;  
    if (strncmp(stdinfo->d_name,".",1)==0continue;  
    if (stdinfo->d_type==8)  
      printf("name=%s/%s\n",strpathname,stdinfo->d_name); 
    if (stdinfo->d_type==4)  
    {
      sprintf(strchdpath,"%s/%s",strpathname,stdinfo->d_name);
      ReadDir(strchdpath);
    }
  } 
  closedir(dir);
}