Android android::base::ReadFileToString 解析

10 篇文章 1 订阅
6 篇文章 0 订阅

概述

代码路径: system/libbase/file.cpp
原型路径: system/libbase/include/android-base/file.h
原型:
bool ReadFileToString(const std::string& path, std::string* content, bool follow_symlinks = false);
用法:
从path 对应的路径中读取文件中的内容到content字符串中。

源码分析

ReadFileToString :

bool ReadFileToString(const std::string& path, std::string* content, bool follow_symlinks) {
  content->clear();		// 清空内容字符串
	// 打开对应路径的文件,使用智能指针
  int flags = O_RDONLY | O_CLOEXEC | O_BINARY | (follow_symlinks ? 0 : O_NOFOLLOW);
  android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(path.c_str(), flags)));
  
  if (fd == -1) {
    return false;
  }
  return ReadFdToString(fd, content);
}

**ReadFdToString **

bool ReadFdToString(borrowed_fd fd, std::string* content) {
  content->clear();

  // Although original we had small files in mind, this code gets used for
  // very large files too, where the std::string growth heuristics might not
  // be suitable. https://code.google.com/p/android/issues/detail?id=258500.
  // 获取文件状态,判断文件是否为空
  struct stat sb;
  if (fstat(fd.get(), &sb) != -1 && sb.st_size > 0) {
  	// 增加字符串的空间大小至文件的总大小
    content->reserve(sb.st_size);	
  }

  char buf[4096] __attribute__((__uninitialized__));
  ssize_t n;
  while ((n = TEMP_FAILURE_RETRY(read(fd.get(), &buf[0], sizeof(buf)))) > 0) {
    content->append(buf, n);
  }
  return (n == 0) ? true : false;
}

struct stat 的定义
获取该结构体的函数

struct stat  
{   
    dev_t       st_dev;     /* ID of device containing file -文件所在设备的ID*/  
    ino_t       st_ino;     /* inode number -inode节点号*/    
    mode_t      st_mode;    /* protection -保护模式?*/    
    nlink_t     st_nlink;   /* number of hard links -链向此文件的连接数(硬连接)*/    
    uid_t       st_uid;     /* user ID of owner -user id*/    
    gid_t       st_gid;     /* group ID of owner - group id*/    
    dev_t       st_rdev;    /* device ID (if special file) -设备号,针对设备文件*/    
    off_t       st_size;    /* total size, in bytes -文件大小,字节为单位*/    
    blksize_t   st_blksize; /* blocksize for filesystem I/O -系统块的大小*/    
    blkcnt_t    st_blocks;  /* number of blocks allocated -文件所占块数*/    
    time_t      st_atime;   /* time of last access -最近存取时间*/    
    time_t      st_mtime;   /* time of last modification -最近修改时间*/    
    time_t      st_ctime;   /* time of last status change - */    
};  
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值