回顾文件
简单代码认识
1 #include<stdio.h>
2 int main(){
3 FILE* fp=fopen("log.txt","w");
4 if(fp==NULL){
5 perror("fopen");
6 return -1;
7 }
8 fclose(fp);
9 return 0;
10 }
以w权限执行时,如果文件不存在就在当前路径下创建新文件。

那么如何向文件中写呢?
介绍函数:fprintf
以w权限时,默认打开文件的时候就会首先把目标文件清空。
文件打开方式
提炼对文件的理解
理解文件
先用和认识系统调用的文件操作
标记位传参的理解
我们如果想按照我们预定的权限的话,加umask(0),这样程序会用我们自己的umask。但是自己设置一个umask系统也有一个umask那么程序执行谁的呢?就近原则,有自己的用自己的,没有的话用系统的

写入操作
1 #include<stdio.h>
2 #include<unistd.h>
3 #include<string.h>
4 #include<sys/types.h>
5 #include<sys/stat.h>
6 #include<fcntl.h>
7 int main(){
8 umask(0);
9 int fp=open("log.txt",O_WRONLY|O_CREAT,0666);
10 if(fp<0){
11 perror("open");
12 return 1;
13 }
14 const char* ch="hello linux!";
15 write(fp,ch,strlen(ch));
16 return 0;
17
18 }
fd: 后面讲, msg:缓冲区首地址, strlen: 本次读取,期望写入多少个字节的数据。 返回值:实际写了多少字节数据
注意strlen在写的时候不需要再+1,\0是c语言的规定跟文件没关系,我们要把有效信息写入。
当然如果想截断清空的话可以加O_TRUNC:
当然也可以追加O_APPEND:
open返回值
通关理解
进程控制xshell终端