文件操作符
- 1.回顾C语言文件接口
- 总结
- 2.系统文件IO
- 2.1 open函数介绍
- 2.2代码测试
- 2.3Q :fd为什么是3?012去哪里了?
- A:
- 3.如何理解Linux下一切皆文件
1.回顾C语言文件接口
- 写文件
#include <stdio.h>
#include <string.h>
int main()
{
FILE *fp = fopen("myfile", "w");
if(!fp){
printf("fopen error!\n");
}
const char *msg = "hello bit!\n";
int count = 5;
while(count--){
fwrite(msg, strlen(msg), 1, fp);
}
fclose(fp);
return 0;
}
- 读文件
#include <stdio.h>
#include <string.h>
int main()
{
FILE *fp = fopen("myfile", "r");
if(!fp){
printf("fopen error!\n");
}
char buf[1024];
const char *msg = "hello bit!\n";
while(1){
//注意返回值和参数,此处有坑,仔细查看man手册关于该函数的说明
ssize_t s = fread(buf, 1, strlen(msg), fp);
if(s > 0){
buf[s] = 0;
printf("%s", buf);
}
if(feof(fp)){
break;
}
}
fclose(fp);
return 0;
}
- 打印到显示器
#include <stdio.h>
#include <string.h>
int main()
{
const char *msg = "hello fwrite\n";
fwrite(msg, strlen(msg), 1, stdout);
printf("hello printf\n");
fprintf(stdout, "hello fprintf\n");
return 0;
}
- stdin & stdout & stderr
- C默认会打开三个输入输出流,分别是stdin, stdout, stderr
- 仔细观察发现,这三个流的类型都是FILE*, fopen返回值类型,文件指针
总结
- 打开方式:
r Open text file for reading.
The stream is positioned at the beginning of the file.
r+ Open for reading and writing.
The stream is positioned at the beginning of the file.
w Truncate(缩短) file to zero length or create text file for writing.
The stream is positioned at the beginning of the file.
w+ Open for reading and writing.
The file is created if it does not exist, otherwise it is truncated.
The stream is positioned at the beginning of the file.
a Open for appending (writing at end of file).
The file is created if it does not exist.
The stream is positioned at the end of the file.
a+ Open for reading and appending (writing at end of file).
The file is created if it does not exist. The initial file position
for reading is at the beginning of the file,
but output is always appended to the end of the file.
2.系统文件IO
2.1 open函数介绍
- pathname: 要打开或创建的目标文件
- flags: 打开文件时,可以传入多个参数选项,用下面的一个或者多个常量进行“或”运算,构成flags。
- 参数:
- O_RDONLY: 只读打开
- O_WRONLY: 只写打开
- O_RDWR : 读,写打开
这三个常量,必须指定一个且只能指定一个 - O_CREAT : 若文件不存在,则创建它。需要使用mode选项,来指明新文件的访问权限
- O_APPEND: 追加写
- 返回值:
成功:新打开的文件描述符
失败:-1
2.2代码测试
#include<stdio.h>
2 #include<sys/types.h>
3 #include <sys/stat.h>
4 #include<fcntl.h>
5 #include <unistd.h>
6 #include <string.h>
7 int main()
8 {
9 umask(0);//取消系统对文件权限的控制
10 //使得文件权限按我们自己设定的执行
11 int fd=open("log.txt", O_WRONLY | O_CREAT | O_APPEND, 0666);//O_WRONLY:写权限 O_CREAT:不存在就创建 O_APPEND:追加写入 0666:权限
12 if(fd<0)
13 {
14 perror("open");
15 return 1;
16 }
17 printf("fd :%d\n",fd);
18
19 int cnt=0;
20
21 const char * str="aaaaaaaaa\n";
22 while(cnt<5)
23 {
24 write(fd,str,strlen(str));
25 cnt++;
26 }
27 close(fd);
28
29 return 0;
30 }
- 结果:
2.3Q :fd为什么是3?012去哪里了?
A:
- fd:0标准输入:键盘
- fd:1标准输出:显示器
- fd:2标准错误:显示器
3.如何理解Linux下一切皆文件