C语言---文件读写

1.判断文件是否能打开

FILE *fp;//定义fp为指向文件类型的指针变量
if((fp=fopen("test.txt","r")) == NULL)//只读打开test.txt,打开不成功
{
    printf("The file can not be opened.\n");    
}
fclose(fp);//关闭文件,fopen后要fclose,正如malloc之后要free

2.检查文件状态

int n;
FILE *fp;
fp = fopen("test.txt","r")); //假设test中保存1~10的整数 
while(!feof(fp)){ //feof()在文件未结束时返回0,结束时返回1
    fscanf(fp,"%d",&n); //格式化输入,将fp所指文件位置起,%d格式的数据,存储到n中,操作结束后,读写位置相应后移
    printf("%d\n",n);   //结果一行输出一个数字 
}
fclose(fp);

3.单个字符读写

FILE* fp;
fp = fopen("test.txt","r"));
char ch;
while(!feof(fp)){
    ch = fgetc(fp);
    printf("%c",ch); //读字符一个一个显示
}
fclose(fp);
FILE* fp;
fp = fopen("test.txt","w"));
char ch;
ch = getchar();
while(ch != EOF){
    fputc(ch,fp); //一个一个字符写入
    ch = getchar();
}
fclose(fp);

4.格式化读写

FILE* fp;
fp = fopen("test.txt","w"));
int i,score;
for(i = 0;i < 10;i++){
    scanf("%d",&score);
    fprintf(fp,"%5d",score); //写入十个整数
}
fclose(fp);
FILE* fp;
fp = fopen("test.txt","r"));
int x,sum = 0;
while(!feof(fp)){
    fscanf(fp,"%d",&x);//读出整数并求和
    sum += x;
}
printf("%d",sum);
fclose(fp);

5.读出格式化数据并存放到结构体中

struct student{ //姓名 学号 英语 语文 数学 科学
    char name[20];
    char ID[20];
    int english;
    int chinese;
    int math;
    int science;
};


//main函数
FILE* fp;
fp = fopen("test.txt","r+"); 
struct student s[100]; 
int i = 0;
while(!feof(fp)){ 
    fscanf(fp,"%s %s %d %d %d %d\n",&s[i].name,&s[i].ID,&s[i].english,&s[i].chinese,&s[i].math,&s[i].science);
	i++;
}
for(int j = 0;j < i;j++){
	printf("%s %s %d %d %d %d\n",s[j].name,s[j].ID,s[j].english,s[j].chinese,s[j].math,s[j].science);
}
fclose(fp);

猜你喜欢

转载自blog.csdn.net/jh8w8m/article/details/87396289