【C++】Linux系统上的对于文件的操作

简要

因为手上的活遇到了文件相关的操作,记录一下相关的代码,以便以后查看。
系统环境: LINUX

创建目录

创建指定路径的文件,利用mkdir函数

/**
 *pathname 表示绝对路径字符串
 *mode 表示文件夹权限
 *return  zero  on  success,  or  -1  if  an  error occurred (in which case, errno is set appropriately)
 *更多信息可以利用 man 2 mkdir 在终端查看
 */
int mkdir(const char *pathname, mode_t mode);

示例:

#include <dirent.h>
void createFolder(std::string folderName) {
    if (access(FOLDER.c_str(), 0) != 0) {
        // if this folder not exist, create a new one.
        int res = mkdir(folderName.c_str(), 0775);
        if(!res) {
            //mkdir successful
        }else {
            // mkdir error,res return errorno
        }
    }else {
    	// else this folder exist, do something
    }
}

修改文件夹或者文件的组用户以及权限

示例:

//直接调用 linux 终端命令
std::string command = "mkdir -p " + FOLDER + "\nchown system.system " + FOLDER + "\nchmod 775 " + FOLDER;
system(command.c_str());
//利用chmod和chown函数实现;
#include <sys/types.h>
#include <pwd.h>
#include <grp.h>

void do_chown (const char *file_path, const char *user_name, const char *group_name) {
  uid_t          uid;
  gid_t          gid;
  struct passwd *pwd;
  struct group  *grp;

  pwd = getpwnam(user_name);
  if (pwd == NULL) {
      die("Failed to get uid");
  }
  uid = pwd->pw_uid;

  grp = getgrnam(group_name);
  if (grp == NULL) {
      die("Failed to get gid");
  }
  gid = grp->gr_gid;

  if (chown(file_path, uid, gid) == -1) {
      die("chown fail");
  }
  if((chmod(file_path, 0775)) == -1){
    ALOGE("%s, chmod error", __FUNCTION__);
  }
}

创建文件

创建文件就很简单了,直接调用 fstream 中的 open 函数就可以创建。

//c++
#include <fstream>
    std::fstream fBinary;
    fBinary.open(fileMapBinary[storeNum], std::fstream::in | std::fstream::out | std::fstream::app | std::fstream::binary);
//c
int fd2 = open("/tmp/test.svg", O_RDWR | O_CREAT, S_IRUSR | S_IRGRP | S_IROTH);

文件读写

因为在使用中主要是读写二进制,所以记录了一下二进制的读写。

// Copy a file
#include <fstream>      
// std::ifstream, std::ofstream

int main () {
  std::ifstream infile ("test.txt",std::ifstream::binary);
  std::ofstream outfile ("new.txt",std::ofstream::binary);

  // get size of file
  infile.seekg (0,infile.end);
  long size = infile.tellg();
  infile.seekg (0);

  // allocate memory for file content
  char* buffer = new char[size];

  // read content of infile
  infile.read (buffer,size);

  // write to outfile
  outfile.write (buffer,size);

  // release dynamically-allocated memory
  delete[] buffer;

  outfile.close();
  infile.close();
  return 0;
}

顺便记录一下 linux 下如何查看二进制文件:

vim -b filename
%!xxd -g 1

获取指定路径下的文件夹中的所有文件

不包含子文件夹

void getAllFile(std::string folderpath, std::vector<std::string> & vs) {
	DIR *dir;
	struct dirent *dtr;
	if ((dir = opendir(folderpath.c_str())) == NULL) {
		//"Open dir error
	}
	while ((dtr = readdir(dir)) != NULL) {
		if (strcmp(dtr->d_name, ".") == 0 || strcmp(dtr->d_name, "..") == 0) continue;
		else if (dtr->d_type == 8) {
			std::string strFile;
			strFile = folderpath;
			strFile += "/";
			strFile += dtr->d_name;
			vs.push_back(strFile);
		}else {
			continue;
		}
	}
	closedir(dir);
}

获取文件的大小

获取文件的信息,利用 stat 结构体

struct stat {
        mode_t     st_mode;       //文件对应的模式,文件,目录等
        ino_t      st_ino;       //inode节点号
        dev_t      st_dev;        //设备号码
        dev_t      st_rdev;       //特殊设备号码
        nlink_t    st_nlink;      //文件的连接数
        uid_t      st_uid;        //文件所有者
        gid_t      st_gid;        //文件所有者对应的组
        off_t      st_size;       //普通文件,对应的文件字节数
        time_t     st_atime;      //文件最后被访问的时间
        time_t     st_mtime;      //文件内容最后被修改的时间
        time_t     st_ctime;      //文件状态改变时间
        blksize_t st_blksize;    //文件内容对应的块大小
        blkcnt_t   st_blocks;     //伟建内容对应的块数量
      };

示例:

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

void getInfo(std::string& filename) {
    struct stat buf;
    stat(filename.c_str(), &buf);
    std::cout << filename << " size:" << buf.st_size << endl;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值