------------->【Linux系统编程/网络编程】(学习目录汇总) <--------------
目录
1.linux man 1 2 3的作用
1、Standard commands (标准命令)
2、System calls (系统调用)
3、Library functions (库函数)
4、Special devices (设备说明)
5、File formats (文件格式)
6、Games and toys (游戏和娱乐)
7、Miscellaneous (杂项)
8、Administrative Commands (管理员命令)
9 其他(Linux特定的), 用来存放内核例行程序的文档。
说明:
系统调用 Linux内核提供的函数
库调用 c语言标准库函数和编译器特定库函数
例子:
man 1 cd
man 2 open
man 3 printf
一个小案例:
C 标准函数和系统函数调用关系。一个 helloworld 如何打印到屏幕。

2.open函数
2.1函数原型
manpage 第二卷(系统调用函数),输入man 2 open指令
open函数如下,有两个版本的

-
open是一个系统函数, 只能在linux系统中使用, windows不支持
-
fopen 是标准c库函数, 一般都可以跨平台使用, 可以这样理解:
在linux中 fopen底层封装了Linux的系统API open
在window中, fopen底层封装的是 window 的 api
2.2函数参数
-
pathname文件路径 -
flags文件打开方式:只读,只写,读写,创建,添加等。O_RDONLY, O_WRONLY, O_RDWR,O_CREAT,O_APPEND,O_TRUNC,O_EXCL,O_NONBLOCK -
mode参数,用来指定文件的权限,数字设定法。文件权限 = mode & ~umask。参数3使用的前提, 参2指定了O_CREAT。 用来描述文件的访问权限。
2.3函数返回值
当open出错时,程序会自动设置errno,可以通过strerror(errno)来查看报错数字的含义
以打开不存在文件为例:

执行该代码,结果如下:

3.close()函数
3.1函数原型
int close(int fd)
3.2函数参数
- fd 表示改文件的文件描述符,open的返回值
- 返回值 成功为0 失败返回-1
小案例:
int fd;
fd=open("tmp.txt",O_RDONLY);
close(fd);
4.read()函数
4.1函数原型
#include <unistd.h>
ssize_t read(int fd, void *buf, size_t count);
4.2函数参数
- fd: 文件描述符,open () 函数的返回值,通过这个参数定位打开的磁盘文件
- buf: 是一个传出参数,指向一块有效的内存,用于存储从文件中读出的数据
- count: buf 指针指向的内存的大小,指定可以存储的最大字节数
4.3函数返回值
- 大于 0: 从文件中读出的字节数,读文件成功
- 等于 0: 代表文件读完了,读文件成功
- -1: 读文件失败了,并设置 errno
如果返回-1: 并且 errno = EAGIN 或 EWOULDBLOCK, 说明不是read失败,而是read在以非阻塞方式读一个设备文件(网络文件),并且文件无数据。
5.write()函数
5.1函数原型
#include <unistd.h>
ssize_t write(int fd, const void *buf, size_t count);
5.2函数参数
- fd: 文件描述符,open () 函数的返回值,通过这个参数定位打开的磁盘文件
- buf: 指向一块有效的内存地址,里边有要写入到磁盘文件中的数据
- count: 要往磁盘文件中写入的字节数,一般情况下就是 buf 字符串的长度,strlen (buf)
5.3函数返回值
- 大于 0: 成功写入到磁盘文件中的字节数
- -1: 写文件失败了
6.小案例:用read()和write()函数实现copy功能
// 文件的拷贝
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <fcntl.h>
int main()
{
// 1. 打开存在的文件english.txt, 读这个文件
int fd1 = open("./english.txt", O_RDONLY);
if(fd1 == -1)
{
perror("open-readfile");
return -1;
}
// 2. 打开不存在的文件, 将其创建出来, 将从english.txt读出的内容写入这个文件中
int fd2 = open("copy.txt", O_WRONLY|O_CREAT, 0664);
if(fd2 == -1)
{
perror("open-writefile");
return -1;
}
// 3. 循环读文件, 循环写文件
char buf[4096];
int len = -1;
while( (len = read(fd1, buf, sizeof(buf))) > 0 )
{
// 将读到的数据写入到另一个文件中
write(fd2, buf, len);
}
// 4. 关闭文件
close(fd1);
close(fd2);
return 0;
}
7.系统调用和库函数比较—预读入缓输出
下面写两个文件拷贝函数,一个用read/write实现,一个用fputc/fgetc实现,比较他们两个之间的速度
fputc/fgetc实现
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <fcntl.h>
int main(void)
{
FILE *fp,*fp_out;
int n = 0;
fp = fopen("hello.c", "r");
if(fp == NULL)
{
perror("fopen error");
exit(1);
}
fp_out = fopen("hello.cp", "w");
if(fp_out == NULL)
{
perror("fopen error");
exit(1);
}
while((n = fgetc(fp)) != EOF)
{
fputc(n, fp_out)

最低0.47元/天 解锁文章
1798

被折叠的 条评论
为什么被折叠?



