Bootstrap

Linux编程----filelo(2)

//标准IO 操作中 ---系统调用的函数 

fdopen()  //将fd 转换  成 FILE *
fileno()  //将FILE *转换 为 fd


FILE *fdopen(int fd,const char *mode);
功能:
   将fd 转换  成 FILE * 
参数:
   @fd    要操作fd
   @mode  打开的模式
返回值: 
   成功 FILE *
   失败 NULL


int fileno(FILE *stream);
功能:
    将FILE *转换 为 fd
参数:
   @stream  要转换流指针 
返回值:
   成功 fd 
   失败 - && errno

 fd = open(,O_RDONLY);
  FILE *fp = fdopen(fd,"a");

#include<stdio.h>
#include<fcntl.h>

int main(int argc, const char *argv[])
{
	int fd = open("1.txt",O_RDONLY);

	if(fd<0)
	{
		perror("open fail");
		return -1;
	}

	printf("fd = %d\n",fd);

	FILE *fp = fdopen(fd,"r");

	if(fp == NULL)
	{
		perror("fdopen fail");
		return -1;
	}

	printf("success\n");

	int fd1 = fileno(fp);
	printf("fileno = %d\n",fd1);

	return 0;
}

 int feof(FILE *stream);
int ferror(FILE *stream);
使用的选择:
  标准IO   --- 可移植性 如果操作只是文本数据 
  文件IO   --- 安全性  操作的是硬件 ---文件IO
 

操作目录:
目录也是一种文件 
类似 标准IO 

//1.打开 
opendir
//2.读写
readdir
//3.关闭 
closedir

DIR *opendir(const char *name); 
功能:
    打开目录,关联一个目录流
参数:
  @name  要打开的目录名 
返回值:
  成功 返回DIR *
  失败 NULL & errno

struct dirent *readdir(DIR *dirp);
功能:
    读取目录项 
参数:
   @dirp 目录流指针 
返回值:
   成功 struct dirent *
   失败 NULL && errno
struct dirent 
{
    ino_t d_ino; /* Inode number */ 
    off_t d_off; /* Not an offset; see below */
    unsigned short d_reclen;/* Length of this record */
    unsigned char d_type;/* Type of file; not supported by all filesystem types */
    char d_name[256]; /* Null-terminated filename */
}

注意:
   读到文件末尾 NULL


int closedir(DIR *dirp);
   功能:
      关闭目录流
   参数:
      @dirp --- 目录流指针 
   返回值:
      成功 0
      失败 -1 &&errno 

实现ls

#include<stdio.h>
#include<dirent.h>

int main(int argc, const char *argv[])
{
	if(argc !=2)
	{
		printf("Usage: %s<failname>",argv[0]);
		return -1;
	}

	DIR * dir = opendir(argv[1]);

	if(dir == NULL)
	{
		perror("opendir fail");
		return -1;
	}

	printf("success\n");

	struct dirent *pdir = NULL;
	while(1)
	{
		pdir = readdir(dir);
		if(pdir == NULL)
		{
			break;
		}
		if(pdir->d_name[0]!='.')
		{
			printf("%s ",pdir->d_name);
		}
	}
	putchar('\n');



	closedir(dir);

	return 0;
}

  实现shell

#include<stdio.h>
#include<dirent.h>

int main(int argc, const char *argv[])
{
	if(argc !=2)
	{
		printf("Usage: %s<failname>",argv[0]);
		return -1;
	}

	DIR * dir = opendir(argv[1]);

	if(dir == NULL)
	{
		perror("opendir fail");
		return -1;
	}

	printf("success\n");


	struct dirent *pdir = NULL;
	int i = 0;
	int j = 0;
	while(1)
	{
		pdir = readdir(dir);
		if(pdir == NULL)
		{
			break;
		}
		if(pdir->d_type == DT_REG)
		{
			i++;

		}else if(pdir->d_type == DT_DIR)
		{
			j++;
		}
	}

			printf("regular=%d directory=%d",i,j);
			putchar('\n');


	closedir(dir);

	return 0;
}

chdir
chdir ("/home/linux"); "../../"
fopen("1.mp4")
int chdir(const char *path);// /home/linux
功能:
    改变当前程序的工作路径
参数:
    path:改变到的路径
返回值:
    成功 返回0
    失败 返回-1

/home/linux/Desktop/Music
"file.txt"

chdir("/root");
"file.txt"

getcwd //pwd 
char *getcwd(char *buf, size_t size);
功能:
    获得当前的工作路径
参数:
    buf:保存工作路径空间的首地址
    size:保存路径空间的长度
返回值:
    成功返回包含路径空间的字符串首地址
    失败返回NULL

#include<stdio.h>
#include<unistd.h>

int main(int argc, const char *argv[])
{
	char buf[1024];

	getcwd(buf,sizeof(buf));

	printf("cwd = %s\n",buf);

	chdir("/home");

	getcwd(buf,sizeof(buf));

	printf("cwd = %s\n",buf);

	return 0;
}

mkdir 
int a  =200;

int mkdir(const char *pathname, mode_t mode);//777  666 --x--x--x
功能:
    创建一个目录
    666-
参数:
    pathname:路径
    mode:
        mode & ~umask  0002
        
返回值:
    成功 返回0
    失败 返回-1

rmdir   rm -fr    rmdir
int rmdir(const char *pathname);
功能:
    删除一个空目录文件
参数:
    pathname:目录文件的名字
返回值:
    成功 返回0
    失败 返回-1

#include<stdio.h>
#include<sys/stat.h>
#include<sys/types.h>

int main(int argc, const char *argv[])
{

	mkdir(argv[1],0777);

//	rmdir("ml");


	return 0;
}

stat 

 int stat(const char *pathname, struct stat *statbuf);
 功能:
    获得文件的状态信息 
 参数:
   @pathname   //需要一个文件名字 
   @statbuf    //用来保存文件的属性信息 
 返回值:
   成功 0
   失败 -1

#include<stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>

int main(int argc, const char *argv[])
{
	struct stat st;

	if(stat(argv[1],&st)<0)
	{
		perror("stat fail");
		return -1;
	}
	printf("name = %s\n",argv[1]);
	printf("link = %ld\n",st.st_nlink);
	printf("size = %ld\n",st.st_size);

	printf("type = %o\n",st.st_mode & S_IFMT);

	printf("%d\n",(st.st_mode & S_IRUSR) == S_IRUSR);
	printf("%d\n",(st.st_mode & S_IWUSR) == S_IWUSR);
	printf("%d\n",(st.st_mode & S_IXUSR) == S_IXUSR);


	(st.st_mode & S_IRUSR) ? putchar('r'):putchar('-');
	(st.st_mode & S_IWUSR) ? putchar('w'):putchar('-');
	(st.st_mode & S_IXUSR) ? putchar('x'):putchar('-');
	putchar('\n');
	return 0;
}

附stst

 struct stat {
               dev_t     st_dev;         /* ID of device containing file */
               ino_t     st_ino;         /* Inode number */
               mode_t    st_mode;        /* File type and mode */ ? unsigned int
               nlink_t   st_nlink;       /* Number of hard links */
               uid_t     st_uid;         /* User ID of owner */
               gid_t     st_gid;         /* Group ID of owner */
               dev_t     st_rdev;        /* Device ID (if special file) */
               off_t     st_size;        /* Total size, in bytes */
               blksize_t st_blksize;     /* Block size for filesystem I/O */
               blkcnt_t  st_blocks;      /* Number of 512B blocks allocated */

               struct timespec st_atim;  /* Time of last access */
               struct timespec st_mtim;  /* Time of last modification */
               struct timespec st_ctim;  /* Time of last status change */

           };
           
           
           st_mode  //unsigned int 
           
           4字节 
           32位 
           
           
           S_IFMT     0170000   bit mask for the file type bit field

           S_IFSOCK   0140000   socket
           S_IFLNK    0120000   symbolic link
           S_IFREG    0100000   regular file
           S_IFBLK    0060000   block device
           S_IFDIR    0040000   directory
           S_IFCHR    0020000   character device
           S_IFIFO    0010000   FIFO

           S_IRWXU     00700   owner has read, write, and execute permission
           S_IRUSR     00400   owner has read permission
           S_IWUSR     00200   owner has write permission
           S_IXUSR     00100   owner has execute permission

           S_IRWXG     00070   group has read, write, and execute permission
           S_IRGRP     00040   group has read permission
           S_IWGRP     00020   group has write permission
           S_IXGRP     00010   group has execute permission

           S_IRWXO     00007   others  (not  in group) have read, write, and
                               execute permission

           S_IROTH     00004   others have read permission
           S_IWOTH     00002   others have write permission
           S_IXOTH     00001   others have execute permission

           
           1 4  0000 
    st_mode 成员变量   
...|17 16 15 |14 13 12 |11 10 9 |8 7 6 |5 4 3 |2 1 0          
       001          100          000      000    000    000 
       001          000          000      000    000    000   
       001          111           000      000    000    000     
                                      010    000  000                                                                    
    
    man stat    //
    man inode   //详细说明 

  实现stat 
  
    File: ls.c

Size: 467           Blocks: 8          IO Block: 4096   regular file
Device: 803h/2051d    Inode: 1318534     Links: 1
Access: (0664/-rw-rw-r--)  Uid: ( 1000/   linux)   Gid: ( 1000/   linux)
Access: 2025-02-17 11:25:46.611546129 +0800
Modify: 2025-02-17 11:25:46.595546514 +0800
Change: 2025-02-17 11:25:46.595546514 +0800
 Birth: -

#include<stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <pwd.h>
#include<time.h>
#include <grp.h>
int main(int argc, const char *argv[])
{
	struct stat st;

	if(lstat(argv[1],&st)<0)
	{
		perror("stat fail");
		return -1;
	}

	printf("name: %s\n",argv[1]);
	printf("size: %ld\t",st.st_size);
	printf("blocks: %ld\t",st.st_blocks);
	printf("blksize: %ld\t",st.st_blksize);


	char type = 0;
	switch(st.st_mode & S_IFMT)
	{
	case S_IFSOCK:
		type = 's';
		printf("socket file\n");
		break;
	case S_IFLNK:
		type = 'l';
		printf("symlink file\n");
		break;
	case S_IFREG:
		type = '-';
		printf("regular file\n");
		break;
	case S_IFBLK:
		type = 'b';
		printf("blocks file\n");
		break;
	case S_IFDIR:
		type = 'd';
		printf("directory file\n");
		break;
	case S_IFCHR:
		type = 'c';
		printf("character file\n");
		break;
	case S_IFIFO:
		type = 'p';
		printf("pipe file\n");
		break;

	}



	printf("Device= %ld\t",st.st_dev);
	printf("Links = %ld\t",st.st_nlink);
	printf("Inode = %ld\n",st.st_ino);


	printf("Access:");
	printf("%#o/%c",st.st_mode&0777,type);
	(st.st_mode & S_IRUSR) ? putchar('r'):putchar('-');
	(st.st_mode & S_IWUSR) ? putchar('w'):putchar('-');
	(st.st_mode & S_IXUSR) ? putchar('x'):putchar('-');

	(st.st_mode & S_IRGRP) ? putchar('r'):putchar('-');
	(st.st_mode & S_IWGRP) ? putchar('w'):putchar('-');
	(st.st_mode & S_IXGRP) ? putchar('x'):putchar('-');

	(st.st_mode & S_IROTH) ? putchar('r'):putchar('-');
	(st.st_mode & S_IWOTH) ? putchar('w'):putchar('-');
	(st.st_mode & S_IXOTH) ? putchar('x'):putchar('-');

	putchar('\t');
	printf("Uid:(%d / %s)\t",st.st_uid,getpwuid(st.st_uid)->pw_name);
	printf("Gid:(%d / %s)\n",st.st_gid,getgrgid(st.st_gid)->gr_name);

	
	struct tm *p = NULL;
	p = localtime(&st.st_atime);
	p = localtime(&st.st_mtime);
	p = localtime(&st.st_ctime);


	printf("Access: %d-%d-%d %d:%d:%d \n",p->tm_year+1900,p->tm_mon+1,p->tm_mday,p->tm_hour,p->tm_min,p->tm_sec);
	printf("Modify: %d-%d-%d %d:%d:%d \n",p->tm_year+1900,p->tm_mon+1,p->tm_mday,p->tm_hour,p->tm_min,p->tm_sec);
	printf("Change: %d-%d-%d %d:%d:%d \n",p->tm_year+1900,p->tm_mon+1,p->tm_mday,p->tm_hour,p->tm_min,p->tm_sec);


	return 0;
}


  

;