今天学习了文件IO函数的使用
函数名 | 功能 | 函数名 | 功能 |
open | 打开文件,获取文件描述符 | close | 关闭文件,释放文件描述符 |
write | 将数据写入到文件中 | read | 将数据从文件中读取出来 |
1、要求创建一个time.txt,存储内容格式如下:
[1] 2022-07-28 17:15:06
[2] 2022-07-28 17:15:07
[3] 2022-07-28 17:15:08
ctrl + c退出程序,过一会儿之后重新启动程序
[1] 2022-07-28 17:15:06
[2] 2022-07-28 17:15:07
[3] 2022-07-28 17:15:08 <-------------------
[4] 2022-07-28 17:16:31
[5] 2022-07-28 17:16:32
所用的功能函数——统计行数
//获取行数函数——返回值为文件目前的行数
int file_count_line(FILE *stream)
{
int count=0;
int c=fgetc(stream);
while(c != EOF)
{
if(c=='\n')
{
count++;
}
c=fgetc(stream);
}
return count;
}
主函数
int main(int argc, const char *argv[])
{
//以可读可写的追加方式打开文件
FILE *fp=fopen("time.txt","a+");
if(NULL==fp)
{
perror("fopen");
return -1;
}
//调用函数获取当前文件的行数
int line=file_count_line(fp);
time_t t; //存放总秒数
struct tm *info=NULL; //存放转换后的时间
while(1)
{
t = time(NULL);
info=localtime(&t);
line++; //让行数发生变化
fprintf(fp,"[%d] %d-%02d-%02d %02d:%02d:%02d\n",\
line,info->tm_year+1900,info->tm_mon+1,info->tm_mday,\
info->tm_hour,info->tm_min,info->tm_sec);
fflush(fp);
sleep(1);
}
//关闭文件
if(fclose(fp)<0)
{
perror("fclose");
return -1;
}
return 0;
}
运行结果
[1] 2022-07-28 19:52:48
[2] 2022-07-28 19:52:49
[3] 2022-07-28 19:52:50
[4] 2022-07-28 19:52:51
[5] 2022-07-28 19:52:52
[6] 2022-07-28 19:52:53
[7] 2022-07-28 19:53:06
[8] 2022-07-28 19:53:07
[9] 2022-07-28 19:53:08
[10] 2022-07-28 19:53:09
[11] 2022-07-28 19:53:10
[12] 2022-07-28 19:53:11
[13] 2022-07-28 19:53:12
[14] 2022-07-28 19:53:13
[15] 2022-07-28 19:53:14
2、拷贝图片(文件IO)
#include<stdio.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<unistd.h>
#include<string.h>
int main(int argc, const char *argv[])
{
//以只读方式打开原图片
int fd = open("./1.jpg",O_RDONLY);
//以可写的方式创建一个目标图片
int fd2 = open("./test.jpg",O_WRONLY|O_CREAT|O_TRUNC,0755);
if(fd <0)
{
fprintf(stderr,"%d处文件打开失败\n",__LINE__);
perror("open");
return -1;
}
if(fd2<0)
{
fprintf(stderr,"%d处文件打开失败\n",__LINE__);
perror("open");
return -1;
}
char str[20]=""; //存放读取出的数据
ssize_t res = 0; //存放读取的数量
while(1)
{
bzero(str,sizeof(str));
res = read(fd,str,sizeof(str));
if(0==res)
{
break;
}
write(fd2,str,res); //写入的时候不要将越界了数据写入到文件中,所以使用res
}
//关闭文件
close(fd);
close(fd2);
return 0;
}