DAY 10
编译器:VS2019;
学习资料 1、B站视频(P50-P53)见链接 【求知讲堂2021C语言/C++视频99天完整版(不断更新中)学完可就业-哔哩哔哩】https://b23.tv/4DzQDY;
文件实例
fopen函数
fopen函数用来打开一个文件。
文件指针名 = fopen (文件名,使用文件方式)
fp = fopen("Text.txt", "rt");
fclose函数
文件一旦使用完毕,应立即关闭文件,以避免文件的数据丢失。
fclose (文件指针)
fclose(fp);
fgetc、fgets函数
逐个读取文件中的字符。 一般形式:fgetc(文件指针)
fgetc(fp);
读取字符串 一般形式:fgets(读取后字符串存放地址,字符数,文件指针)
fgets(str,100,fp);
#include<stdio.h>
#include<string.h>
#pragma warning (disable:4996)
int main(void)
{
FILE* fp;
char str[100] = { 0 };
fp = fopen("Text.txt", "at+");
if (fp == NULL)
{
puts("文件打开失败。");
exit(0);
}
printf("请输入字符串:");
char temp[100];
gets(temp);
strcat(str,temp);
fputs(str, fp);
fclose(fp);
return 0;
}
ferror函数
- 读写文件出错检测函数:ferror 。
- 调用格式:ferror(文件指针)。
- 功能:检查文件在用各种输入输出函数时是否出错。如ferror返回 0 表示未出错,否则表示有错。
#include<stdio.h>
#pragma warning (disable:4996)
int main (void)
{
FILE* fp;
char ch;
fp = fopen("Text.txt", "rt");
if (fp == NULL)
{
puts("文件读取失败。");
exit(0);
}
while ((ch = fgetc(fp)) != EOF)
{
putchar(ch);
}
putchar('\n');
if (ferror(fp))
{
puts("读取出错。");
}
else
{
puts("读取成功。");
}
fclose(fp);
return 0;
}
fwrite、fread函数
数据块读写函数:fread和fwrite
fread(b, size, 5, fp);
fwrite(a, size, 5, fp);
#include<stdio.h>
#pragma warning (disable:4996)
int main(void)
{
int a[5];
int b[5];
FILE* fp;
int size = sizeof(int);
fp = fopen("Text.txt", "rb+");
if (fp == NULL)
{
puts("读取失败。");
}
for (size_t i = 0; i < 5; i++)
{
scanf("%d", &a[i]);
}
fwrite(a, size, 5, fp);
rewind(fp);
fread(b, size, 5, fp);
for (size_t i = 0; i < 5; i++)
{
printf("%d", b[i]);
}
printf("\n");
fclose(fp);
return 0;
}
fseek函数
fseek(fp, sizeof(struct Student), SEEK_SET);
#include<stdio.h>
#pragma warning (disable:4996)
struct Student
{
char name[20];
int num;
int age;
float score;
};
int main(void)
{
struct Student boys[3];
struct Student boy;
struct Student* Pboy;
FILE* fp;
Pboy = boys;
fp = fopen("Text.txt", "wb+");
if (fp == NULL)
{
printf("不能打开该文件。\n");
getch();
exit(1);
}
printf("请输入学生的相关数据:\n");
for (size_t i = 0; i < 3; i++)
{
scanf("%s %d %d %f", &Pboy->name, &Pboy->num, &Pboy->age, &Pboy->score);
Pboy++;
}
fwrite(boys, sizeof(struct Student), 3, fp);
fseek(fp, sizeof(struct Student), SEEK_SET);
fread(&boy, sizeof(struct Student), 1, fp);
printf("%s %d %d %f\n", boy.name, boy.num, boy.age, boy.score);
fclose(fp);
return 0;
}
|