系统调用实现 open close write等等
/*
#include <unistd.h>
ssize_t read(int fd, void *buf, size_t count);
参数:
- fd:文件描述符,open得到的,通过这个文件描述符操作某个文件
- buf:需要读取数据存放的地方,数组的地址(传出参数)
- count:指定的数组的大小
返回值:
- 成功:
>0: 返回实际的读取到的字节数
=0:文件已经读取完了
- 失败:-1 ,并且设置errno #include <unistd.h>
ssize_t write(int fd, const void *buf, size_t count);
参数:
- fd:文件描述符,open得到的,通过这个文件描述符操作某个文件
- buf:要往磁盘写入的数据,数据
- count:要写的数据的实际的大小
返回值:
成功:实际写入的字节数
失败:返回-1,并设置errno
*/
#include <unistd.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h> int main() { // 1.通过open打开english.txt文件
int srcfd = open("english.txt", O_RDONLY);
if(srcfd == -1) {
perror("open");
return -1;
} // 2.创建一个新的文件(拷贝文件)
int destfd = open("cpy.txt", O_WRONLY | O_CREAT, 0664);
if(destfd == -1) {
perror("open");
return -1;
} // 3.频繁的读写操作
char buf[1024] = {0};
int len = 0; len = read(srcfd, buf, sizeof(buf));
write(destfd, buf, len);
// while((len = read(srcfd, buf, sizeof(buf))) > 0) {
// write(destfd, buf, len);
// } // 4.关闭文件
close(destfd);
close(srcfd); return 0;
}
lseek 实现文件当前光标的移动
/*
标准C库的函数
#include <stdio.h>
int fseek(FILE *stream, long offset, int whence); Linux系统函数
#include <sys/types.h>
#include <unistd.h>
off_t lseek(int fd, off_t offset, int whence);
参数:
- fd:文件描述符,通过open得到的,通过这个fd操作某个文件
- offset:偏移量
- whence:
SEEK_SET
设置文件指针的偏移量
SEEK_CUR
设置偏移量:当前位置 + 第二个参数offset的值
SEEK_END
设置偏移量:文件大小 + 第二个参数offset的值
返回值:返回文件指针的位置 作用:
1.移动文件指针到文件头
lseek(fd, 0, SEEK_SET); 2.获取当前文件指针的位置
lseek(fd, 0, SEEK_CUR); 3.获取文件长度
lseek(fd, 0, SEEK_END); 4.拓展文件的长度,当前文件10b, 110b, 增加了100个字节
lseek(fd, 100, SEEK_END)
注意:需要写一次数据 */ #include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h> int main() { int fd = open("hello.txt", O_RDWR); if(fd == -1) {
perror("open");
return -1;
} // 扩展文件的长度
int ret = lseek(fd, 100, SEEK_END);
if(ret == -1) {
perror("lseek");
return -1;
} // 写入一个空数据
write(fd, " ", 1); // 关闭文件
close(fd); return 0;
}



stat实现对文件权限和类型的描述
/*
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h> int stat(const char *pathname, struct stat *statbuf);
作用:获取一个文件相关的一些信息
参数:
- pathname:操作的文件的路径
- statbuf:结构体变量,传出参数,用于保存获取到的文件的信息
返回值:
成功:返回0
失败:返回-1 设置errno int lstat(const char *pathname, struct stat *statbuf);
参数:
- pathname:操作的文件的路径
- statbuf:结构体变量,传出参数,用于保存获取到的文件的信息
返回值:
成功:返回0
失败:返回-1 设置errno */ #include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <stdio.h> int main() { struct stat statbuf; int ret = stat("a.txt", &statbuf); if(ret == -1) {
perror("stat");
return -1;
} printf("size: %ld\n", statbuf.st_size); return 0;
}
使用stat实现ls-l

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <pwd.h>
#include <grp.h>
#include <time.h>
#include <string.h> // 模拟实现 ls -l 指令
// -rw-rw-r-- 1 nowcoder nowcoder 12 12月 3 15:48 a.txt
int main(int argc, char * argv[]) { // 判断输入的参数是否正确
if(argc < 2) {
printf("%s filename\n", argv[0]);
return -1;
} // 通过stat函数获取用户传入的文件的信息
struct stat st;
int ret = stat(argv[1], &st);
if(ret == -1) {
perror("stat");
return -1;
} // 获取文件类型和文件权限
char perms[11] = {0}; // 用于保存文件类型和文件权限的字符串 switch(st.st_mode & S_IFMT) {
case S_IFLNK:
perms[0] = 'l';
break;
case S_IFDIR:
perms[0] = 'd';
break;
case S_IFREG:
perms[0] = '-';
break;
case S_IFBLK:
perms[0] = 'b';
break;
case S_IFCHR:
perms[0] = 'c';
break;
case S_IFSOCK:
perms[0] = 's';
break;
case S_IFIFO:
perms[0] = 'p';
break;
default:
perms[0] = '?';
break;
} // 判断文件的访问权限 // 文件所有者
perms[1] = (st.st_mode & S_IRUSR) ? 'r' : '-';
perms[2] = (st.st_mode & S_IWUSR) ? 'w' : '-';
perms[3] = (st.st_mode & S_IXUSR) ? 'x' : '-'; // 文件所在组
perms[4] = (st.st_mode & S_IRGRP) ? 'r' : '-';
perms[5] = (st.st_mode & S_IWGRP) ? 'w' : '-';
perms[6] = (st.st_mode & S_IXGRP) ? 'x' : '-'; // 其他人
perms[7] = (st.st_mode & S_IROTH) ? 'r' : '-';
perms[8] = (st.st_mode & S_IWOTH) ? 'w' : '-';
perms[9] = (st.st_mode & S_IXOTH) ? 'x' : '-'; // 硬连接数
int linkNum = st.st_nlink; // 文件所有者
char * fileUser = getpwuid(st.st_uid)->pw_name; // 文件所在组
char * fileGrp = getgrgid(st.st_gid)->gr_name; // 文件大小
long int fileSize = st.st_size; // 获取修改的时间
char * time = ctime(&st.st_mtime); char mtime[512] = {0};
strncpy(mtime, time, strlen(time) - 1); char buf[1024];
sprintf(buf, "%s %d %s %s %ld %s %s", perms, linkNum, fileUser, fileGrp, fileSize, mtime, argv[1]); printf("%s\n", buf); return 0;
}

文件属性操作

access实现获取文件属性
#include <unistd.h>
#include <stdio.h> int main() { int ret = access("a.txt", F_OK);
if(ret == -1) {
perror("access");
} printf("文件存在!!!\n"); return 0;
}
chmod改变文件权限
/*
#include <sys/stat.h>
int chmod(const char *pathname, mode_t mode);
修改文件的权限
参数:
- pathname: 需要修改的文件的路径
- mode:需要修改的权限值,八进制的数
返回值:成功返回0,失败返回-1 */
#include <sys/stat.h>
#include <stdio.h>
int main() { int ret = chmod("a.txt", 0777); if(ret == -1) {
perror("chmod");
return -1;
} return 0;
}
truncate改变文件字节数
/*
#include <unistd.h>
#include <sys/types.h>
int truncate(const char *path, off_t length);
作用:缩减或者扩展文件的尺寸至指定的大小
参数:
- path: 需要修改的文件的路径
- length: 需要最终文件变成的大小
返回值:
成功返回0, 失败返回-1
*/ #include <unistd.h>
#include <sys/types.h>
#include <stdio.h> int main() { int ret = truncate("b.txt", 5); if(ret == -1) {
perror("truncate");
return -1;
} return 0;
}

目录操作

mkdir
/*
#include <sys/stat.h>
#include <sys/types.h>
int mkdir(const char *pathname, mode_t mode);
作用:创建一个目录
参数:
pathname: 创建的目录的路径
mode: 权限,八进制的数
返回值:
成功返回0, 失败返回-1
*/ #include <sys/stat.h>
#include <sys/types.h>
#include <stdio.h> int main() { int ret = mkdir("aaa", 0777); if(ret == -1) {
perror("mkdir");
return -1;
} return 0;
}
rename
/*
#include <stdio.h>
int rename(const char *oldpath, const char *newpath); */
#include <stdio.h> int main() { int ret = rename("aaa", "bbb"); if(ret == -1) {
perror("rename");
return -1;
} return 0;
}
chdir修改进程的工作目录
/*

    #include <unistd.h>
int chdir(const char *path);
作用:修改进程的工作目录
比如在/home/nowcoder 启动了一个可执行程序a.out, 进程的工作目录 /home/nowcoder
参数:
path : 需要修改的工作目录 #include <unistd.h>
char *getcwd(char *buf, size_t size);
作用:获取当前工作目录
参数:
- buf : 存储的路径,指向的是一个数组(传出参数)
- size: 数组的大小
返回值:
返回的指向的一块内存,这个数据就是第一个参数 */
#include <unistd.h>
#include <stdio.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h> int main() { // 获取当前的工作目录
char buf[128];
getcwd(buf, sizeof(buf));
printf("当前的工作目录是:%s\n", buf); // 修改工作目录
int ret = chdir("/home/nowcoder/Linux/lesson13");
if(ret == -1) {
perror("chdir");
return -1;
} // 创建一个新的文件
int fd = open("chdir.txt", O_CREAT | O_RDWR, 0664);
if(fd == -1) {
perror("open");
return -1;
} close(fd); // 获取当前的工作目录
char buf1[128];
getcwd(buf1, sizeof(buf1));
printf("当前的工作目录是:%s\n", buf1); return 0;
}



目录遍历:

目录遍历
/*
// 打开一个目录
#include <sys/types.h>
#include <dirent.h>
DIR *opendir(const char *name);
参数:
- name: 需要打开的目录的名称
返回值:
DIR * 类型,理解为目录流
错误返回NULL // 读取目录中的数据
#include <dirent.h>
struct dirent *readdir(DIR *dirp);
- 参数:dirp是opendir返回的结果
- 返回值:
struct dirent,代表读取到的文件的信息
读取到了末尾或者失败了,返回NULL // 关闭目录
#include <sys/types.h>
#include <dirent.h>
int closedir(DIR *dirp); */
#include <sys/types.h>
#include <dirent.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h> int getFileNum(const char * path); // 读取某个目录下所有的普通文件的个数
int main(int argc, char * argv[]) { if(argc < 2) {
printf("%s path\n", argv[0]);
return -1;
} int num = getFileNum(argv[1]); printf("普通文件的个数为:%d\n", num); return 0;
} // 用于获取目录下所有普通文件的个数
int getFileNum(const char * path) { // 1.打开目录
DIR * dir = opendir(path); if(dir == NULL) {
perror("opendir");
exit(0);
} struct dirent *ptr; // 记录普通文件的个数
int total = 0; while((ptr = readdir(dir)) != NULL) { // 获取名称
char * dname = ptr->d_name; // 忽略掉. 和..
if(strcmp(dname, ".") == 0 || strcmp(dname, "..") == 0) {
continue;
} // 判断是否是普通文件还是目录
if(ptr->d_type == DT_DIR) {
// 目录,需要继续读取这个目录
char newpath[256];
sprintf(newpath, "%s/%s", path, dname);
total += getFileNum(newpath);
} if(ptr->d_type == DT_REG) {
// 普通文件
total++;
} } // 关闭目录
closedir(dir); return total;
}

dup 和dup2 文件描述符操作



dup2相当于吧new与以前做close,然后把new指向lod指向的文件

dup复制文件描述符
/*
#include <unistd.h>
int dup(int oldfd);
作用:复制一个新的文件描述符
fd=3, int fd1 = dup(fd),
fd指向的是a.txt, fd1也是指向a.txt
从空闲的文件描述符表中找一个最小的,作为新的拷贝的文件描述符 */ #include <unistd.h>
#include <stdio.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <string.h> int main() { int fd = open("a.txt", O_RDWR | O_CREAT, 0664); int fd1 = dup(fd); if(fd1 == -1) {
perror("dup");
return -1;
} printf("fd : %d , fd1 : %d\n", fd, fd1); close(fd); char * str = "hello,world";
int ret = write(fd1, str, strlen(str));
if(ret == -1) {
perror("write");
return -1;
} close(fd1); return 0;
}
dup2 关闭new与之前的文件,并重新指向lod的文件描述符
/*
#include <unistd.h>
int dup2(int oldfd, int newfd);
作用:重定向文件描述符
oldfd 指向 a.txt, newfd 指向 b.txt
调用函数成功后:newfd 和 b.txt 做close, newfd 指向了 a.txt
oldfd 必须是一个有效的文件描述符
oldfd和newfd值相同,相当于什么都没有做
*/
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h> int main() { int fd = open("1.txt", O_RDWR | O_CREAT, 0664);
if(fd == -1) {
perror("open");
return -1;
} int fd1 = open("2.txt", O_RDWR | O_CREAT, 0664);
if(fd1 == -1) {
perror("open");
return -1;
} printf("fd : %d, fd1 : %d\n", fd, fd1); int fd2 = dup2(fd, fd1);
if(fd2 == -1) {
perror("dup2");
return -1;
} // 通过fd1去写数据,实际操作的是1.txt,而不是2.txt
char * str = "hello, dup2";
int len = write(fd1, str, strlen(str)); if(len == -1) {
perror("write");
return -1;
} printf("fd : %d, fd1 : %d, fd2 : %d\n", fd, fd1, fd2); close(fd);
close(fd1); return 0;
}

fcntl控制文件描述符

fcntl 中途改变文件描述符的内容,权限等等
/*

    #include <unistd.h>
#include <fcntl.h> int fcntl(int fd, int cmd, ...);
参数:
fd : 表示需要操作的文件描述符
cmd: 表示对文件描述符进行如何操作
- F_DUPFD : 复制文件描述符,复制的是第一个参数fd,得到一个新的文件描述符(返回值)
int ret = fcntl(fd, F_DUPFD); - F_GETFL : 获取指定的文件描述符文件状态flag
获取的flag和我们通过open函数传递的flag是一个东西。 - F_SETFL : 设置文件描述符文件状态flag
必选项:O_RDONLY, O_WRONLY, O_RDWR 不可以被修改
可选性:O_APPEND, O)NONBLOCK
O_APPEND 表示追加数据
NONBLOK 设置成非阻塞 阻塞和非阻塞:描述的是函数调用的行为。
*/ #include <unistd.h>
#include <fcntl.h>
#include <stdio.h>
#include <string.h> int main() { // 1.复制文件描述符
// int fd = open("1.txt", O_RDONLY);
// int ret = fcntl(fd, F_DUPFD); // 2.修改或者获取文件状态flag
int fd = open("1.txt", O_RDWR);
if(fd == -1) {
perror("open");
return -1;
} // 获取文件描述符状态flag
int flag = fcntl(fd, F_GETFL);
if(flag == -1) {
perror("fcntl");
return -1;
}
flag |= O_APPEND; // flag = flag | O_APPEND // 修改文件描述符状态的flag,给flag加入O_APPEND这个标记
int ret = fcntl(fd, F_SETFL, flag);
if(ret == -1) {
perror("fcntl");
return -1;
} char * str = "nihao";
write(fd, str, strlen(str)); close(fd); return 0;
}

文件IO示例程序的更多相关文章

  1. ACEXML解析XML文件——简单示例程序

    掌握了ACMXML库解析XML文件的方法后,下面来实现一个比较完整的程序. 定义基本结构 xml文件格式如下 <?xml version="1.0"?> <roo ...

  2. 第七篇:两个经典的文件IO程序示例

    前言 本文分析两个经典的C++文件IO程序,提炼出其中文件IO的基本套路,留待日后查阅. 程序功能 程序一打印用户指定的所有文本文件,程序二向用户指定的所有文本文件中写入数据. 程序一代码及其注释 # ...

  3. 两个经典的文件IO程序示例

    前言 本文分析两个经典的C++文件IO程序,提炼出其中文件IO的基本套路,留待日后查阅. 程序功能 程序一打印用户指定的所有文本文件,程序二向用户指定的所有文本文件中写入数据. 程序一代码及其注释 # ...

  4. 《嵌入式linux应用程序开发标准教程》笔记——6.文件IO编程

    前段时间看APUE,确实比较详细,不过过于详细了,当成工具书倒是比较合适,还是读一读这种培训机构的书籍,进度会比较快,遇到问题时再回去翻翻APUE,这样的效率可能更高一些. <嵌入式linux应 ...

  5. JAVA 基础编程练习题50 【程序 50 文件 IO】

    50 [程序 50 文件 IO] 题目:有五个学生,每个学生有 3 门课的成绩,从键盘输入以上数据(包括学生号,姓名,三门课成绩), 计算出平均成绩,将原有的数据和计算出的平均分数存放在磁盘文件&qu ...

  6. RocketMQ消费者示例程序

    转载请注明出处:http://www.cnblogs.com/xiaodf/ 本博客实现了一个简单的RocketMQ消费者的示例,MQ里存储的是经过Avro序列化的消息数据,程序读取数据并反序列化后, ...

  7. RocketMQ生产者示例程序

    转载请注明出处:http://www.cnblogs.com/xiaodf/ 本示例展示了一个RocketMQ producer的简单实现,通过解析文本文件获取输入数据,将数据经过Avro序列化后发送 ...

  8. epub、ocf等常用电子书格式浅析----附JAVA示例程序

    一. 电子书介绍 转载请注明http://www.cnblogs.com/xckk/p/6020324.html Epub(Electronic Publication)是一个完全开放和免费的电子书标 ...

  9. 将ZIP文件添加到程序集资源文件然后在运行时解压文件

    今天做安装打包程序研究,之前同事将很多零散的文件发布成一个安装文件夹给用户,这样体验不好,我希望将所有文件打包成一个.net程序,运行此程序的时候自解压然后执行后续的安装步骤. 解决过程: 1,将所有 ...

随机推荐

  1. SNAT技术

    前面在讲解 firewall-config 工具的功能时,曾经提到了 SNAT(Source Network Address Translation,源网络地址转换)技术.SNAT 是一种为了解决 I ...

  2. C# 将OFD转为PDF

    OFD格式的文档是一种我国独有的国家标准版式的文档,在不同场景需求中,可以通过格式转换的方法将PDF转为OFD,或者将OFD转为PDF.本次内容,将通过C#程序介绍如何实现由OFD到PDF的转换,并附 ...

  3. js正则表达式 (.+)与(.+?)

    (.+)默认是贪婪匹配 (.+?)为惰性匹配 疑问号让.+的搜索模式从贪婪模式变成惰性模式. var str = 'aaa<div style="font-color:red;&quo ...

  4. Java线程--BlockingQueue使用

    原创:转载需注明原创地址 https://www.cnblogs.com/fanerwei222/p/11871704.html Java线程--BlockingQueue使用 阻塞队列就是内容满了之 ...

  5. 如何按规定的格式向mysql中导入数据

    1.首先我们拿到数据,数据必须按照一定的格式书写的.如用|区分字段,换行区分row 12107 | 心情1 | 今天的心情很不好啊. 12108 | 天气 | 今天天气还行. 12109 | 臭美 | ...

  6. Pandas中Series与Dataframe的初始化

    (一)Series初始化 1.通过列表,index自动生成 se = pd.Series(['Tom', 'Nancy', 'Jack', 'Tony']) print(se) 2.通过列表,指定in ...

  7. 将自己的web应用发布到Tomcat

    方法一:(用这个方法最好先把ROOT文件夹备份好,不建议使用) 1,打开tomcat 的目录,在webapps 的目录下, 把命名为ROOT 的文件夹删掉, 然后把自己的war 包更名为 ROOT.w ...

  8. HTTP状态码100、200、300、400、500、600的含义

    1xx (临时响应)表示临时响应并需要请求者继续执行操作的状态代码. 100 (继续) 请求者应当继续提出请求. 服务器返回此代码表示已收到请求的第一部分,正在等待其余部分. 101 (切换协议) 请 ...

  9. Solution -「ARC 058C」「AT 1975」Iroha and Haiku

    \(\mathcal{Description}\)   Link.   称一个正整数序列为"俳(pái)句",当且仅当序列中存在连续一段和为 \(x\),紧接着连续一段和为 \(y ...

  10. Vue2.0源码学习(4) - 合并配置

    合并配置 通过之前的源码学习,我们已经了解到了new Vue主要有两种场景,第一种就是在外部主动调用new Vue创建一个实例,第二个就是代码内部创建子组件的时候自行创建一个new Vue实例.但是无 ...