系统编程函数之文件目录操作


1、文件的创建打开:creat 、open
NAME
        open, openat, creat - open and possibly create a file
SYNOPSIS
        #include <sys/types.h>
       #include <sys/stat.h>
       #include <fcntl.h>
        int open(const char *pathname, int flags);    flags包括: O_RDONLY (只读), O_WRONLY (只写), or O_RDWR (读写)
       int open(const char *pathname, int flags, mode_t mode);
        int creat(const char *pathname, mode_t mode);
       int openat(int dirfd, const char *pathname, int flags);
       int openat(int dirfd, const char *pathname, int flags, mode_t mode);
RETURN VALUE
       open(), openat(), and creat() return the new file descriptor, or -1 if an error occurred (in which case,  errno  is  set  appropri‐
       ately).
封装:
     int openFile(const char *pathname, int flags)      
     {   
         int fd = -1;
         fd = open(pathname, flags| O_CREAT , 0664); (除了O_CREAT,还有 O_APPEND O_ASYNC O_CLOEXEC )
         if (-1 == fd)
         {
             perror("open");
             exit(EXIT_FAILURE);
         }
         return fd;
     }
使用:int fd = openFile(argv[1], O_RDONLY);
别忘了close(fd);  !!!


2、读文件:read
NAME
       read - read from a file descriptor
SYNOPSIS
        #include <unistd.h>
        ssize_t read(int fd, void *buf, size_t count);
RETURN VALUE
       On  success,  the  number of bytes read is returned (zero indicates end of file), and the file position is advanced by this number.
       It is not an error if this number is smaller than the number of bytes requested; this may happen for example  because  fewer  bytes
       are actually available right now (maybe because we were close to end-of-file, or because we are reading from a pipe, or from a ter‐
       minal), or because read() was interrupted by a signal.  See also NOTES.
       On error, -1 is returned, and errno is set appropriately.  In this case, it is left unspecified whether the file position (if  any)
       changes.
封装:
     ssize_t readDataFromFile(int fd, void *buf, size_t count)
     {
         ssize_t iReaded = 0;
         if (NULL != buf)
         {   
             int ret = -1;
             while (1)
             {
                 if (count > 4096)
                 {
                     ret = read(fd, buf, 4096);
                 }
                 else
                 {
                     ret = read(fd, buf, count);
                 }
                 if (-1 == ret)
                 {
                     perror("read");
                     break;
                 }
                 else if (0 == ret)
                 {
                     break;
                 }
                 iReaded += ret;
                 count -= ret;
                 buf = (char *)buf + ret;
             }     
         }
              return iReaded;
     }
使用:STU tmp;    int ret = -1;    ret = read(fd, &tmp, sizeof(STU));
      
3、文件的写入:write
NAME
       write - write to a file descriptor
SYNOPSIS
        #include <unistd.h>
        ssize_t write(int fd, const void *buf, size_t count);
RETURN VALUE
       On  success,  the  number  of bytes written is returned (zero indicates nothing was written).  It is not an error if this number is
       smaller than the number of bytes requested; this may happen for example because the disk device was filled.  See also NOTES.

       On error, -1 is returned, and errno is set appropriately.

       If count is zero and fd refers to a regular file, then write() may return a failure status if one of the errors below is  detected.
       If  no  errors are detected, or error detection is not performed, 0 will be returned without causing any other effect.  If count is
       zero and fd refers to a file other than a regular file, the results are not specified.
封装:
ssize_t writeDataToFile(int fd, void *buf, size_t count)
{
    ssize_t iWrited = 0;
    if (NULL != buf)
    {
        int ret = 0;
        while (count)
        {
            if (count > 4096)
            {
                ret = write(fd, buf, 4096);
            }
            else
            {
                ret = write(fd, buf, count);
            }
            if (-1 == ret)
                 {
                     perror("read");
                     break;
                 }
                 else if (0 == ret)
                 {
                     break;
                 }
            iWrited += ret;
            count -= ret;
            buf = (char *)buf + ret;
        }
    }
    return iWrited;
}
使用:STU tmp;    int ret = -1;    ret = write(fd, &tmp, sizeof(STU));


4、设置文件读写位置 lseek
NAME
       lseek - reposition read/write file offset
SYNOPSIS
       #include <sys/types.h>
       #include <unistd.h>
        off_t lseek(int fd, off_t offset, int whence);   whence包括: SEEK_SET (首部), SEEK_CUR (当前位置), SEEK_END (尾部)
RETURN VALUE
       Upon  successful completion, lseek() returns the resulting offset location as measured in bytes from the beginning of the file.  On
       error, the value (off_t) -1 is returned and errno is set to indicate the error.
使用:int size = seek_fileposition(fd, 0, SEEK_END);   读取文件大小
    //获得第四个学生
    offset = 3 * sizeof(STU);
    lseek(fd, offset, SEEK_SET);
    read(fd, &tmp, sizeof(STU));



1、目录的创建 mkdir
NAME
       mkdir, mkdirat - create a directory
SYNOPSIS
       #include <sys/stat.h>
       #include <sys/types.h>
        int mkdir(const char *pathname, mode_t mode);
       #include <fcntl.h>           /* Definition of AT_* constants */
       #include <sys/stat.h>
       int mkdirat(int dirfd, const char *pathname, mode_t mode);
RETURN VALUE
       mkdir() and mkdirat() return zero on success, or -1 if an error occurred (in which case, errno is set appropriately).
ERRORS (错误发生的种类)
       EACCES The  parent  directory  does  not allow write permission to the process, or one of the directories in pathname did not allow
              search permission.  (See also path_resolution(7).)
       EDQUOT The user's quota of disk blocks or inodes on the filesystem has been exhausted.
       EEXIST pathname already exists (not necessarily as a directory).  This includes the case where pathname is a  symbolic  link,  dan‐
              gling or not.
       EFAULT pathname points outside your accessible address space.
       ELOOP  Too many symbolic links were encountered in resolving pathname.
       EMLINK The number of links to the parent directory would exceed LINK_MAX.
       ENAMETOOLONG
              pathname was too long.
       ENOENT A directory component in pathname does not exist or is a dangling symbolic link.
       ENOMEM Insufficient kernel memory was available.
       ENOSPC The device containing pathname has no room for the new directory.
       ENOSPC The new directory cannot be created because the user's disk quota is exhausted.
       ENOTDIR
              A component used as a directory in pathname is not, in fact, a directory.
       EPERM  The filesystem containing pathname does not support the creation of directories.
       EROFS  pathname refers to a file on a read-only filesystem.
       The following additional errors can occur for mkdirat():
       EBADF  dirfd is not a valid file descriptor.
       ENOTDIR
              pathname is relative and dirfd is a file descriptor referring to a file other than a directory.
使用:mkdir(argc[1], 0777);


2、查看目录属性 access
NAME
       access, faccessat - check user's permissions for a file
SYNOPSIS
       #include <unistd.h>
       int access(const char *pathname, int mode);
       #include <fcntl.h>           /* Definition of AT_* constants */
       #include <unistd.h>
       int faccessat(int dirfd, const char *pathname, int mode, int flags);
RETURN VALUE
       On success ( all requested permissions granted, or mode is F_OK and the file exists), zero is returned.  On error (at least one  bit
       in  mode  asked  for a permission that is denied, or mode is F_OK and the file does not exist, or some other error occurred), -1 is
       returned, and errno is set appropriately.
使用:
            if (-1 == access(caPathname, F_OK))
            {
                mkdir(caPathname, 0777);
            }


3、打开目录文件 opendir
OPENDIR (3)                                                Linux Programmer's Manual                                              OPENDIR(3)
NAME
       opendir, fdopendir - open a directory
SYNOPSIS
       #include <sys/types.h>
       #include <dirent.h>
       DIR *opendir(const char *name);
       DIR *fdopendir(int fd);
RETURN VALUE
       The opendir() and fdopendir() functions return a pointer to the directory stream.  On error, NULL is returned,  and  errno  is  set
       appropriately.
使用:
        DIR *dir = opendir(name);
        if(NULL == dir)
        {
                perror("opendir");
                exit(EXIT_FALURE);
        }


4、读取目录 readdir
READDIR (3)                                               Linux Programmer's Manual                                              READDIR(3)
NAME
       readdir, readdir_r - read a directory
SYNOPSIS
        #include <dirent.h>
        struct dirent *readdir(DIR *dirp);
       int readdir_r(DIR *dirp, struct dirent *entry, struct dirent **result);
   Feature Test Macro Requirements for glibc (see feature_test_macros(7)):
       readdir_r():
           _POSIX_C_SOURCE >= 1 || _XOPEN_SOURCE || _BSD_SOURCE || _SVID_SOURCE || _POSIX_SOURCE
DESCRIPTION
       The  readdir()  function  returns  a  pointer  to  a dirent structure representing the next directory entry in the directory stream
       pointed to by dirp.  It returns NULL on reaching the end of the directory stream or if an error occurred.
       On Linux, the dirent structure is defined as follows:
          struct dirent {
               ino_t          d_ino;       /* inode number */
               off_t          d_off;       /* not an offset; see NOTES */
               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]; /* filename */
           };
       DT_BLK      This is a block device.
       DT_CHR      This is a character device.
        DT_DIR      This is a directory.
       DT_FIFO     This is a named pipe (FIFO).
       DT_LNK      This is a symbolic link.
        DT_REG      This is a regular file.
       DT_SOCK     This is a UNIX domain socket.
       DT_UNKNOWN  The file type is unknown.
ETURN VALUE
       On  success,  readdir()  returns  a  pointer to a dirent structure.  (This structure may be statically allocated; do not attempt to
       free(3) it.)  If the end of the directory stream is reached, NULL is returned and errno is not changed.  If an error  occurs,  NULL
       is returned and errno is set appropriately.
       The  readdir_r() function returns 0 on success.  On error, it returns a positive error number (listed under ERRORS).  If the end of
       the directory stream is reached, readdir_r() returns 0, and returns NULL in *result.
使用:
    DIR *dir = open_dir(argv[1]);
    struct dirent *pdirent = NULL;
        pdirent = readdir(dir);
if(NULL != pdirent)
{
            printf("%s\t", pdirent->d_name)
}





  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值