2021寒假专题8
C语言的文件操作可以唠嗑的还真不少,除了基本的语法还有一些案例
这里讨论文件的fgetc/fputc、fgets/fputs、fread/fwrite
fseek,rewind,ftell,fprintf/fscanf、sscanf/sprintf、二进制文本,系统文件指针以及一些特定的操作等等,内容样例比较多
include <stdio.h>
typedef struct
{
char name[64];
int age;
}Hero;
Hero heros[5];
int main()
{
//FILE是结构体 /*
FILE* fp=fopen("E:\\c语言之家\\文件读写.txt","r");
if(fp==NULL)
{
printf("无法打开文件");
return 0;
}
char ch1=fgetc(fp);//fgetc读取一个字符
printf("%c",ch1);
char ch2=fgetc(fp);//fgetc读取下个字符,每读一次文件指针往后偏移一个
printf("%c",ch2);
char ch;
//EOF宏
while((ch=fgetc(fp))!=EOF)
{
printf("%c",ch);
}
//fgets读取一行
char str[200];
//fgets(str,200,fp);
//printf("%s",str);
//fgets读完一行也可以移动到下一行
/*while(fgets(str,200,fp))//fgets读不到时会返回一个NULL
{
//fgets返回值返回到str
printf("%s",str);
} */
}
include <stdio.h>
#include <string.h>
typedef struct
{
char name[20];
int age;
}People;
People heros[5]={{"tzp",18},{"tzp",18},{"tzp",18},{"tzp",18},{"tzp",18}};
int main()
{
FILE* fp=fopen("E:\\c语言之家\\文件读写.txt","w");//w清空写
if(fp==NULL)
{
printf("无法打开文件");
return 0;
}
//fputc('A',fp);
//char *p="Apple\r\n";
//fputs(p,fp);
//fwrite(p,sizeof(char),strlen(p),fp);//第三个参数确定块的个数
//fwrite不仅可以读入字符串,还可以读入数字,直接读入记事本可能会出现乱码,但只要可以正确得读回来说明是可行的
//可以读入结构体,但要基于值编码,用wb,rb
//int num=45678;
//fwrite(&num,sizeof(num),1,fp);
fclose(fp);
//char str[200]={0};
//fseek(fp,10,SEEK_SET);//文件指针的定位,10,SEEK_SET表示从文件开始移动10字节开始
//fseek(fp,10,SEEK_CUR);//10,SEEK_CUR表示从当前位置开始移动10个字节
//fseek(fp,0,SEEK_END);//指针指向末尾
/*fseek(fp,-1,SEEK_END);
char ch=0;
int len=0;
while(fread(&ch,1,1,fp))//只读取最后一行的内容
{
if(ch=='\n') break;
fseek(fp,-2,SEEK_CUR);
len++;
}*/
//fputs(str,fp);
//printf(str);
//fread(&ch,1,1,fp);
//printf("%c",ch);
/* rewind(fp);//将文件指针移到开头
fseek(fp,0,SEEK_END);
//ftell获取文件光标的位置 可以获得文件
int nSize=ftell(fp);//文件末尾大小
printf("%d",nSize);
fclose(fp);
return 0; /*
}
include <stdio.h>
//功能强大的fread/fwrite
typedef struct
{
char name[64];
int age;
}Hero;
Hero heros[5]={{"tzp",18},{"tzp",19},{"tzp",20},{"tzp",21},{"tzp",22}};
Hero hero_ans[5];
int main()
{
FILE* fp=fopen("E:\\c语言之家\\文件读写.txt","wb");
if(fp==NULL) printf("NO\n");
fwrite(heros,sizeof(Hero),5,fp);
fclose(fp);
fp=fopen("E:\\c语言之家\\文件读写.txt","rb");
fread(hero_ans,sizeof(Hero),5,fp);
for(int i=0;i<5;i++) printf("%s %d\n",hero_ans[i].name,hero_ans[i].age);
fclose(fp);
//指针的移动
fp=fopen("E:\\c语言之家\\文件读写.txt","rb");
if(fp==NULL) printf("NO\n");
Hero temp;
//fseek(fp,sizeof(Hero)*3,SEEK_SET);
fseek(fp,-(long)sizeof(Hero)*2,SEEK_END);//读倒数第二行,sizeof的返回值是无符号,需要强制转换为有符号
fread(&temp,sizeof(Hero),1,fp);
fclose(fp);
printf("%s %d",temp.name,temp.age);
}
二进制文件与文本文件的一个区别
换行,在Windows下 文本文件 程序换行\n,磁盘是\r\n
二进制文件 程序换行\n 磁盘\n
在Linux下\n即可
样例:持续从键盘上输入信息直到输入quiz
include <stdio.h>
#include <string.h>
int main()
{
FILE* fp;
fp=fopen("文件读写.txt","w");
if(fp==NULL) printf("打开文件失败");
while(1)
{
char buf[1024]={0};
fgets(buf,sizeof(buf)-1,stdin);//从键盘输入
//判断
if(strncmp(buf,"quiz",4)==0) break;
int i=0;
while(buf[i]!='\0') fputc(buf[i++],fp);
}
fclose(fp);
}

浙公网安备 33010602011771号