linux c 文件操作。
因为最近要看socket,而linux的哲学之一是一切东西皆文件,socket同时起源于linux,所以想看看linux的文件操作。
1 什么是系统编程?
linux下系统编程是指程序员使用系统调用或者c语言所携带的库函数设计和编写具有一定功能的程序。(系统调用,如open,write,read函数)
注意:
(1)shell下通过man mkdir 获得的是命令的帮助信息,man 2 mkdir获得的是系统调用的帮助信息,man 3 **获得的是库函数的帮助信息。
(2)gcc不会自动链接某些库,需要在编译的时候使用 -l<库名> -L<库所在目录>
2.linux的文件结构?
linux是一个操作系统,linux文件子系统是其中的一个模块。它的主要功能是管理文件,存储空间分配,文件访问权限维护,对文件的的各种操作。
注意:
(1)linux是树形文件目录管理。
(2)绝对路径:从根目录开始。
(3)相对目录:从当前目录开始。
(4)linux以统配符“*”代表文件中任意字符或者字符串。以统配符“?”代表任意一个字符。
(5)目录也是一种文件,目录文件的内容是该目录的目录项,目录项是该目录下的文件和目录的相关信息。
3.linux文件系统模型。
文件归根究底都是数据,而数据都要存储到磁盘或者硬盘上的,操作系统通过文件系统对磁盘进行管理,对磁盘的访问是要通过设备驱动程序进行的,而对设备驱动程序的访问可以有两种方式,第一种设备驱动程序本身提供的接口(这种方式不是很安全),第二种vfs(虚拟文件系统)提供给上层应用程序的接口。
注意:
(1)vfs只有当系统启动时候才存在。和/proc一样。
4.文件类型?
普通文件:r表示。目录文件:d表示。字符特殊文件:c表示。块特殊文件:b表示。0
注意:fifo进程间通信,socket网络进程间通信。
5。文件的创建打开关闭,文件的读写系统调用注意:
(1)在编写跨平台的程序时,最好使用c语言标准库函数(fopen,fclose,fwrite,fseek),因为create,opne使用文件描述符表示文件,而文件描述符是linux独有的。
(2)linux下一个进程最多打开256个文件。
6.编写一小段代码
功能:输入一串字符输出到文件hello
1 #include <sys/types.h> //open, create 2 #include <sys/stat.h> //open,create 3 #include <fcntl.h> //open,create 4 #include <stdio.h> 5 #include <unistd.h> //read,write 6 #include <errno.h> 7 #include <stdlib.h> 8 #include <string.h> 9 10 int main(int argc, char **argv) 11 { 12 int fd;//文件描述符 13 // int i;//和写入的字符个数进行比较,判断是否完全写入文件。 14 char a[30];//记录要写入文件的字符 15 16 if((fd = open("/home/xiong/hello", O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR)) == -1) 17 { 18 perror("open"); 19 exit(0); 20 } 21 else 22 { 23 printf("open success\n"); 24 } 25 26 printf("please input:"); 27 scanf("%s", a); 28 29 if(write(fd, (const void *)a, strlen(a)) == strlen(a)) 30 { 31 printf("success input\n"); 32 // printf("%d\n", sizeof(a)); 33 } 34 35 if(close(fd) == -1) 36 { 37 printf("exit fd error"); 38 } 39 }
遇到的问题
(1)open的第一个参数必须是绝对路径命,不能是“~”。“.”之类的。
(2)strlen与sizeof的区别,好久没写过c有点忘了。 write返回判断时候球了。
(3)创建新文件的时候必须指定新文件的权限。
(4)scanf()会读入换行符(换行符的ascil为10,空格为13)
1 #include <sys/types.h> //open, create 2 #include <sys/stat.h> //open,create 3 #include <fcntl.h> //open,create 4 #include <stdio.h> 5 #include <unistd.h> //read,write 6 #include <errno.h> 7 #include <stdlib.h> 8 #include <string.h> 9 10 int main(int argc, char **argv) 11 { 12 int fd;//文件描述符 13 int i;//记录read读入的字符数 14 char buf[30];//读入缓冲区 15 16 if((fd = open("/home/xiong/hello", O_RDWR)) == -1) 17 { 18 perror("open"); 19 exit(0); 20 } 21 else 22 { 23 printf("success open\n"); 24 } 25 26 while((i = read(fd, (void *)buf, 3)) != 0) 27 { 28 29 printf("%s %d %d\n", buf, i, buf[2]); 30 } 31 32 if(i == -1) 33 { 34 perror("reead"): 35 } 36 37 close(fd); 38 }
注意:
(1)create()只能以写的方式打开文件,所以它叫做create的原因吧。
这里就是常用的几个东西,后面如果用到修改权限等等,我会继续添加的,。
toucao下,妈单的markdown,害得我这个博文差点丢了。