当前位置:网站首页>【C语言进阶】文件操作(二)
【C语言进阶】文件操作(二)
2022-06-29 09:36:00 【皓仔活在今天】
1、文件随机读写
1.1、fseek函数
fseek函数的作用,根据文件指针的位置和偏移量来定位文件指针
随机读文件
#include <stdio.h>
#include <errno.h>
#include <string.h>
int main()
{
FILE* pf = fopen("text.txt", "r");
if (pf == NULL)
{
printf("%s\n", strerror(errno));
}
//读文件
int ch = fgetc(pf);
printf("%c\n", ch);
ch = fgetc(pf);
printf("%c\n", ch);
//定位文件指针
//fseek(pf, 1, SEEK_CUR);//三个参数(流、偏移量、文件指针位置)
//fseek(pf, 3, SEEK_SET);
fseek(pf, -1, SEEK_END);
ch = fgetc(pf);
printf("%c\n", ch);
fclose(pf);
pf = NULL;
return 0;
}
随机写文件
#include <stdio.h>
#include <errno.h>
#include <string.h>
int main()
{
FILE* pf = fopen("text.txt", "w");
if (pf == NULL)
{
printf("%s\n", strerror(errno));
}
//写文件
int ch = 0;
for (ch = 'a'; ch <= 'z'; ch++)
{
fputc(ch, pf);
}
//定位文件指针
fseek(pf, -1, SEEK_END);//可以在指定位置修改你写入的内容
fputc('#', pf);
fclose(pf);
pf = NULL;
return 0;
}
1.2、ftell函数
ftell函数的作用是告诉你当前文件指针的偏移量(告诉你当前文件指针位置)
#include <stdio.h>
#include <errno.h>
#include <string.h>
int main()
{
FILE* pf = fopen("text.txt", "r");
if (pf == NULL)
{
printf("%s\n", strerror(errno));
}
//读文件
int ch = fgetc(pf);
printf("%c\n", ch);
ch = fgetc(pf);
printf("%c\n", ch);
int ret = ftell(pf);
printf("%d\n", ret);
fclose(pf);
pf = NULL;
return 0;
}
1.3、rewind函数
rewind函数的作用是把文件指针偏移量置为 0,文件指针重新指向文件开头
#include <stdio.h>
#include <errno.h>
#include <string.h>
int main()
{
FILE* pf = fopen("text.txt", "r");
if (pf == NULL)
{
printf("%s\n", strerror(errno));
}
//读文件
int ch = fgetc(pf);
printf("%c\n", ch);
ch = fgetc(pf);
printf("%c\n", ch);
int ret = ftell(pf);
printf("%d\n", ret);
rewind(pf);
ret = ftell(pf);
printf("%d\n", ret);
fclose(pf);
pf = NULL;
return 0;
}
2、判断文件读取是否结束
1、文本文件读取是否结束
判断返回值是否为EOF(fgetc)或者NULL(fgets)
例如:
fgetc判断是否为EOF;
fgets判断返回值是否为NULL;
2、二进制文件读取结束判断,判断返回值是否小于实际要读取的个数
例如:
fread判断返回值是否小于实际要读的个数
3、文件缓冲区
文件在储存的时候,会先将数据储存在缓冲区中,缓冲区存满之后,一次性写入文件中
文件读出数据时也是一样,会先将数据储存在缓冲区中,缓冲区存满之后,一次性读出来
只要你关闭文件,就会刷新缓冲区
边栏推荐
猜你喜欢
随机推荐
Reading notes of CLR via C -clr boarding and AppDomain
Given the values of two integer variables, the contents of the two values are exchanged (C language)
MySQL innodb每行数据长度的限制
Talk about threads and concurrency
LVGL库入门教程 - 动画
Ora-01950 does not have permission on tablespace
The process of updating a record in MySQL
Analysis of liferayportal jsonws deserialization vulnerability (cve-2020-7961)
Report card of regional industrial Internet market, the second place of Baidu intelligent yunkaiwu
Offensive and defensive world re insfsay
产品力不输比亚迪,吉利帝豪L雷神Hi·X首月交付1万台
AQS之Atomic详解
查看CSDN的博客排名
MySQL中innodb_page_cleaners详解
AQS之ReentrantLock源码解析
Excel日期及数字格式处理
如何优雅的写 Controller 层代码?
I would like to know how to open an account for free online stock registration? In addition, is it safe to open a mobile account?
共2600页!又一份神级的面试手册面世~
《CLR via C#》读书笔记-加载与AppDomain








