一、流的定位
(1)给定一个bmp图片文件名获得图片的宽度和高度
#include<stdio.h>
int main(void)
{
FILE *fp = NULL;
int high = 0;
int wid = 0;
fp = fopen("suibian.bmp","r");
if(fp == NULL)
{
perror("fail");
return-1;
}
fseek(fp,18,SEEK_SET);
fread(&high,4,1,fp);
fread(&wid,4,1,fp);
printf("高:%d宽:%d\n+",high,wid);
fclose(fp);
return 0;
}
二、文件IO
(1)标准IO:
1.打开文件 fopen
2.读写文件 fgetc fputc
fgets fputs
fscanf fprintf
fread fwrite
3.关闭文件 fclose
(2)文件IO:
1.打开文件 open
2.读写文件 read write
3.关闭文件 close
(3)flags:打开方式
必须包含:O_RDONLY、O_WRONLY、O_RDWR 三个其中之一
O_CREAT 文件不存在创建
O_TRUNC 文件存在清0
O_APPEND 追加
O_EXCL 文件存在报错
O_NONBLOCK 非阻塞
O_ASYNC 异步IO
mode:权限
只要有O_CREAT标识,表示需要加上权限:
rwx rwx rwx
rw- rw- r--
110 110 100
0 6 6 4
(4)标准IO和文件IO的共同作用函数
"r" O_RONLY
"r+" O_RDWR
"w" O_WRONLY | O_CREAT | O_TRUNC, 0664
"w+" O_RDWR | O_CREAT | O_TRUNC, 0664
"a" O_WRONLY | O_CREAT | O_APPEND, 0664
"a+" O_RDWR | O_CREAT | O_APPEND, 0664
#include <stdio.h>
#include<sys/stat.h>
#include<sys/types.h>
#include<fcntl.h>
#include<string.h>
#include<unistd.h>
int main(void)
{
int fd = 0;
char tempbuff[4096] = {"hello world"};
fd = open("a.txt",O_WRONLY|O_CREAT|O_TRUNC,0664);
if(-1 == fd)
{
perror("fail");
return -1;
}
write(fd,"hello world",11);//\n 不打印
write(fd,tempbuff,strlen(tempbuff));
close(fd);
return 0;
}
占用三个:
close(0),会停止in...
0 STDIN_FILENO -> stdin
1 STDOUT_FILENO -> stdout
2 STDERR_FILENO -> stderr
(5)其他函数接口
三、标准IO和文件的区别
1.标准IO是库函数
2.文件IO是系统调用
3.标准IO是针对于文件IO的封装
4.标准IO是有缓存的
5.文件IO是没有缓存的
6.标准IO主要用于操作普通文件
7.文件IO可以操作设备文件、进程间通信的文件、普通文件(Linux系统下的一切文件均可以使用文件IO)
库函数:是针对于系统调用的封装,可以在Windows或者Linux系统中使用
系统调用:是Linux内核中的函数接口,只能在Linux系统中使用
四、拓展:LINux中时间的获取
#include <time.h>
#include <stdio.h>
#include <unistd.h>
int main(void)
{
time_t t;
struct tm *ptm = NULL;
struct tm tmp;
tmp.tm_hour = 17;
tmp.tm_min = 25;
tmp.tm_sec = 0;
tmp.tm_year = 2024-1900;
tmp.tm_mon = 8-1;
tmp.tm_mday = 1;
t = mktime(&tmp);
printf("t = %ld\n", t);
t = time(NULL);
printf("t = %ld\n", t);
#if 0
// t = time(NULL);
while (1)
{
time(&t);
ptm = localtime(&t);
printf("%04d-%02d-%02d %02d:%02d:%02d\r", ptm->tm_year+1900, ptm->tm_mon+1, \
ptm->tm_mday, ptm->tm_hour, ptm->tm_min, ptm->tm_sec);
fflush(stdout);
sleep(1);
}
#endif
return 0;
}