1、打开文件
fopen(文件名,使用文件方式);(注意是双引号不是单引号)
使用文件方式有:”r"(只读) “w”(只写) “a”(追加)
以二进制文件为对象时: “rb”(只读) “wb”(只写) “ab”(追加)
FILE *fp; //fp是指向文件的指针变量
if((fp=fopen("file.txt","r"))==NULL){
printf("fail to open file\n");
exit(0); //要写 #include <stdlib.h>
}
2、关闭文件
fclose(文件指针)
fclose(fp);//将缓冲区的数据写入文件再关闭
3、读写字符&字符串:
fgetc(fp) 从fp指向的文件读入一个字符
fgets(str,n,fp) 从fp指向的文件读入一个长为n-1的字符串,存放在字符数组str中(最后一个字符自动为’\0’),如果遇到换行符或者文件结束符EOF则结束,换行符也读入。
fputc(ch,fp) 把字符ch写到fp指向的文件中
fputs(str,fp) 把str指向的字符串写到fp指向的文件中
4、格式化方法读写文件
fscanf(文件指针,格式字符串,输入列表);//输入列表注意是否需要加&
fprintf(文件指针,格式字符串,输出列表)
int i; float f;
fscanf(fp,”%d %f”,&i,&f);
5、二进制方式读写一组数据
fread(buffer,size,count,fp);
fwrite(buffer,size,count,fp);
size:一个数据项的字节数
count:要读写的数据项数
fread(&stud[i],sizeof(struct Student_type),1,fp);//每次从文件中读入一个组stud大小的元素进数组stud中
fwrite(&stud[i],sizeof(struct Student_type),1,fp);//将元素stud[i]写入文件中
题目(2018数计院复试笔试题最后一题)
实现从data.txt文件从读取学生信息(建立学生信息结构体)并建立链表,然后按字母表升序排序将其排序(学生姓名全为英文名,但有大小写的不同),最后将排序好的学生信息从链表输出到另一个文件中(将姓名第一个字母调整为大写,其余字母均为小写)。题目中给定了三个函数名,分别为输入函数(实现从data.txt读取学生信息,返回值类型为指针类型)、输出函数(将已排序的学生信息按格式要求输出到另一个文件中)、main函数,做题时必须按照这个框架写。
(用fscanf和fprintf是最方便的了)
输入文件:
zZZ 90
aAA 80
bBB 85
代码:
#include <stdio.h> //使用标准函数库中的输入输出函数
#include <stdlib.h>
#include <string.h>
#include <iostream>
using namespace std;
struct Stu
{
char name[20];
int score;
Stu* next;
};
int cnt=0;//学生数
Stu *Input(char filename[])
{
Stu *head=(Stu*)malloc(sizeof(Stu));//这个头指针要有分配空间
FILE *fp;
if((fp=fopen(filename,"r"))==NULL){
printf("fail1"); exit(0);
}
Stu *p=head;
while(!feof(fp))
{
cnt++;
Stu *tem=(Stu*)malloc(sizeof(Stu));
fscanf(fp,"%s%d",tem->name,&tem->score);
p->next=tem;
p=p->next;
}
p->next=NULL;
fclose(fp);
return head;
}
void Output(char filename[],Stu* stu)
{
FILE *fp;
if((fp=fopen(filename,"w"))==NULL){
printf("fail2"); exit(0);
}
Stu *p=stu->next;//此时p指向第一个结点
while(p)
{
char *name=p->name;
strlwr(name); //先全部转换成小写
name[0]-='a'-'A'; //然后将首字母改成大写
fprintf(fp,"%s %d\n",name,p->score);
p=p->next;
}
fclose(fp);
}
int main()
{
char c1[]="data2018.txt",c2[]="student2018.txt";
Stu *stu=Input(c1);
while(cnt--)//对链表进行冒泡排序
{
Stu *pre=stu,*p=stu->next,*q;
if(!p) break;
q=p->next;
while(q)
{
if(strcmp(p->name,q->name)>0)
{
//交换p、q结点在链表中的位置
pre->next=q;
p->next=q->next;
q->next=p;
//恢复p、q指针的相对位置,即pre->p->q
Stu *tem=p; p=q; q=tem;
}
pre=pre->next;
p=p->next;
q=q->next;
}
}
Output(c2,stu);
}
输出文件(结果):
Aaa 80
Bbb 85
Zzz 90