根据数据的组织形式,可以将文件分为文本文件和二进制文件。通俗讲,文本文件就是你能看懂的,而二进制文件是你看不懂的!
假设已经定义了一个文件指针
FILE *fp;
有了文件指针,意味着你就可以对文件为所欲为。
int main()
{
FILE *fp;
if((fp = fopen("E:\\data.txt","r")) == NULL){
printf("文件打开失败!\n");
exit(EXIT_FAILURE);
}
int ch;
while((ch = getc(fp)) != EOF){
putchar(ch);
}
fclose(fp); /*文件有打开,必须要有关闭*/
return 0;
}
int main()
{
FILE *fp1;
FILE *fp2;
int ch;
if((fp1 = fopen("E:\\data.txt","r")) == NULL){
printf("文件打开失败!\n");
exit(EXIT_FAILURE);
}
if((fp2 = fopen("E:\\copy.txt","w")) == NULL){
printf("文件打开失败!\n");
exit(EXIT_FAILURE);
}
while((ch = fgetc(fp1)) != EOF){
fputc(ch,fp2);
}
fclose(fp1);
fclose(fp2);
return 0;
}
int main()
{
FILE *fp;
char buffer[N];
if((fp = fopen("E:\\test.txt","w")) == NULL){
printf("文件打开失败\n");
exit(EXIT_FAILURE);
}
/*往文件中写入*/
fputs("I love FishC.com\n",fp);
fputs("I love China\n",fp);
fputs("I love my parent",fp);
fclose(fp);
if((fp = fopen("E:\\test.txt","r")) == NULL){
printf("文件打开失败\n");
exit(EXIT_FAILURE);
}
/*读取*/
while(!feof(fp)){
fgets(buffer,N,fp);
printf("%s\n",buffer);
}
return 0;
}
int main()
{
FILE *fp;
char buffer[N];
if((fp = fopen("E:\\test.txt","w")) == NULL){
printf("文件打开失败\n");
exit(EXIT_FAILURE);
}
/*往文件中写入*/
fputs("I love FishC.com\n",fp);
fputs("I love China\n",fp);
fputs("I love my parent\n",fp); //出问题的一行
fclose(fp);
if((fp = fopen("E:\\test.txt","r")) == NULL){
printf("文件打开失败\n");
exit(EXIT_FAILURE);
}
/*读取*/
while(!feof(fp)){
fgets(buffer,N,fp);
printf("%s\n",buffer);
}
return 0;
}
NOTE:
若在读取字符中遇到EOF,则eof指示器被设置;但是如果再没有读到任何字符之前就遇到了EOF,则str指示器指向的位置保持原来的位置不变,即“I love my parent”被读取了两次。
#include
#include
#define N 3
struct Stu
{
int num;
char name[24];
float score;
}stu[N];
int main()
{
FILE *fp;
int i;
struct Stu temp;
for(i = 0;i < N;i++){
scanf("%d %s %f",&stu[i].num,stu[i].name,&stu[i].score);
}
if((fp = fopen("E:\\test1.txt","wb")) == NULL){
printf("文件打开失败\n");
exit(EXIT_FAILURE);
}
for(i = 0;i < N;i++){
if(fwrite(&stu[i],sizeof(struct Stu),1,fp) != 1){
printf("写入文件失败\n");
}
}
fclose(fp);
/*读取文件*/
if((fp = fopen("E:\\test1.txt","rb")) == NULL){
printf("文件打开失败\n");
exit(EXIT_FAILURE);
}
for(i=0;i<N;i++){
fread(&temp,sizeof(struct Stu),1,fp);
printf("num = %d,name = %s,socre = %.2f\n",temp.num,temp.name,temp.score);
}
fclose(fp);
return 0;
}
#include
#include
#define N 3
struct Stu
{
int num;
char name[24];
float score;
}stu[N],somebody;
int main()
{
FILE *fp;
int i;
printf("请输入学生的相关信息\n");
for(i = 0;i < N;i++){
scanf("%d %s %f",&stu[i].num,stu[i].name,&stu[i].score);
}
if((fp = fopen("E:\\text2.txt","w")) == NULL){
printf("文件打开失败\n");
exit(EXIT_FAILURE);
}
for(i=0;i<N;i++){
if(fwrite(&stu[i],sizeof(struct Stu),1,fp) != 1){
printf("文件打开失败\n");
}
}
fclose(fp);
if((fp = fopen("E:\\text2.txt","r")) == NULL){
printf("文件打开失败\n");
exit(EXIT_FAILURE);
}
printf("当前位置指针:%d\n",ftell(fp));
fseek(fp,sizeof(struct Stu),0);
fread(&somebody,sizeof(struct Stu),1,fp);
printf("num = %d, name = %s, score = %f",somebody.num,somebody.name,somebody.score);
fclose(fp);
return 0;
}
其他函数的详细讲解,请到小甲鱼(小甲鱼牛逼)的网站上自行学习。函数详解。