文件三步曲:
打开读写关闭
#include <stdio.h>
/**
* fputc()
*/
void test1()
{
FILE *fp=fopen(
"/Users/fzl/Desktop/2.txt",
"w");
if(fp==NULL)
{
perror(
"fopen failed");
}
char ch=
'a';
fputc(ch, fp);
fclose(fp);
}
/**
* fgetc()
*/
void test2()
{
FILE *fp=fopen(
"/Users/fzl/Desktop/2.txt",
"r");
if(fp==NULL)
{
perror(
"fopen failed");
}
char ch=
0;
ch=fgetc(fp);
printf(
"ch=%c\n",ch);
fclose(fp);
}
/**
* fprintf()
*/
void test3()
{
int a=
8;
char ch=
'a';
FILE *fp=fopen(
"/Users/fzl/Desktop/2.txt",
"w");
if(fp==NULL)
{
perror(
"fopen failed");
}
fprintf(fp,
"a=%d,ch=%c\n",a,ch);
fclose(fp);
}
/**
*fscanf()
*/
void test4()
{
int a=
0;
char ch=
0;
FILE *fp=fopen(
"/Users/fzl/Desktop/2.txt",
"r");
if(fp==NULL)
{
perror(
"fopen failed");
}
fscanf(fp,
"a=%d,ch=%c\n",&a,&ch);
printf(
"a=%d\nch=%c\n",a,ch);
fclose(fp);
}
/**
* fputs()
*/
void test5()
{
char name[
20]=
"rose";
FILE *fp=fopen(
"/Users/fzl/Desktop/2.txt",
"w");
if(fp==NULL)
{
perror(
"fopen failed");
}
fputs(name, fp);
fclose(fp);
}
/**
* fgets()
*/
void test6()
{
char name[
20];
FILE *fp=fopen(
"/Users/fzl/Desktop/2.txt",
"r");
if(fp==NULL)
{
perror(
"fopen failed");
}
fgets(name, sizeof(name), fp);
printf(
"name=%s",name);
fclose(fp);
}
/**
fseek(),ftell()
*/
void test7()
{
char ch;
FILE *fp=fopen(
"/Users/fzl/Desktop/2.txt",
"r");
if(fp==NULL)
{
perror(
"fopen failed");
}
fseek(fp,
0, SEEK_END);
printf(
"文件大小=%ld\n",ftell(fp));
ch=fgetc(fp);
printf(
"ch=%c\n",ch);
fclose(fp);
}
void test8()
{
typedef struct Student
{
int age;
char name[
20];
}Student;
Student stu={
10,
"rose"};
FILE *fp=fopen(
"/Users/fzl/Desktop/2.txt",
"w");
if(fp==NULL)
{
perror(
"fopen failed");
}
fwrite(&stu, sizeof(stu),
1, fp);
fclose(fp);
}
/**
* fread()
*/
void test9()
{
typedef struct Student
{
int age;
char name[
20];
}Student;
Student stu;
FILE *fp=fopen(
"/Users/fzl/Desktop/2.txt",
"r");
if(fp==NULL)
{
perror(
"fopen failed");
}
fread(&stu, sizeof(stu),
1, fp);
printf(
"stu的name=%s,age=%d\n",stu.name,stu.age);
fclose(fp);
}
void test10()
{
typedef struct Student
{
int age;
char name[
20];
}Student;
Student stu[
3]={
{
10,
"rose"},
{
20,
"jack"},
{
30,
"white"}
};
FILE *fp=fopen(
"/Users/fzl/Desktop/2.txt",
"w");
if(fp==NULL)
{
perror(
"fopen failed");
}
int i=
0;
for (; i<
3; i++)
{
fwrite(&stu[i], sizeof(Student),
1, fp);
}
fclose(fp);
}
void test11()
{
typedef struct Student
{
int age;
char name[
20];
}Student;
Student stu[
3];
FILE *fp=fopen(
"/Users/fzl/Desktop/2.txt",
"r");
if(fp==NULL)
{
perror(
"fopen failed");
}
int i=
0;
for (; i<
3; i++)
{
fread(&stu[i], sizeof(Student),
1, fp);
printf(
"stu[%d].name=%s,age=%d\n",i,stu[i].name,stu[i].age);
}
fclose(fp);
}
int main()
{
test11();
return 0;
}
转载请注明原文地址: https://ju.6miu.com/read-5416.html