1.导包
#include
#include
#include
2.文件读取
//根据地址读取内容 绝对地址 比如/sdcard/a.txt
void FileReadString(char *path,char *buf) {int fd = open(path, O_RDONLY);if (fd == -1) {printf("can not open the file\n");}char bufs[1024] = { "\0" };int len = read(fd, bufs, 1024);printf("%s\nlen=%d\n", bufs, len);strcpy(buf, bufs);close(fd);}调用方法:
char buff[1024];
FileReadString("/sdcard/0.txt", buff);
printf("buff========%s\n", buff);
3.文件存储
//存储到某个文件 绝对地址 比如/sdcard/a.txt
void FileWriteString(char *path, char *bufs) {FILE *fd = fopen(path, "w+");/* 创建并打开文件 */if (fd){fputs(bufs, fd);fclose(fd);}
}调用方式:
FileWriteString("/sdcard/01.txt", "需要存储的字符串");
4.文件删除
//文件删除功能
_Bool removeFile(char *path) {if (remove(path) == 0) {printf("Removed %s.\n", path);return 0;}else {perror("remove");return 1;}return 0;
}调用方式:
removeFile("/sdcard/0.txt");
5.创建文件夹
//判断文件地址是否存在
int file_exist(char *path)
{if (access(path, F_OK) == 0) {return 0;}return -1;
}// 创建文件夹
void createFolder(char *path)
{// 文件夹不存在则创建文件夹if (file_exist(path) == -1){mkdir(path);}
}调用方式:
createFolder("/sdcard/test/");
6.遍历文件夹
#include /*标准输入输出定义*/
#include /*标准函数库定义*/
#include /*Unix 标准函数定义*/
#include /*字符串功能函数*/int trave_dir(char* path, char filename[][256])
{int len = 0;DIR *d; //声明一个句柄struct dirent *file; //readdir函数的返回值就存放在这个结构体中struct stat sb;if (!(d = opendir(path))){printf("error opendir %s!!!\n", path);return -1;}while ((file = readdir(d)) != NULL){//把当前目录.,上一级目录..及隐藏文件都去掉,避免死循环遍历目录if (strncmp(file->d_name, ".", 1) == 0)continue;strcpy(filename[len++], file->d_name); //保存遍历到的文件名 printf("len==%d\n", len);}closedir(d);return len;
}使用方式:
int i;
char filenames[256][256];
int lent = trave_dir("/sdcard/test/", filenames);
for (i = 0; i < lent; i++)
{if (filenames[i] != NULL) {printf("%s\t", filenames[i]);}
}
我是在linux+arm主板上运行的,所以我的地址是以sdcard来使用