C语言文件操作
函数原型
- size_t fread(void *buffer, size_t size, size_t count, FILE *stream);
- size_t fwrite(const void *buffer, size_t size, size_t count, FILE *stream);
功能
fread和fwrite用于读写记录,这里的记录是指一串固定长度的字节,比如一个int、一个结构体或者一个定长数组。参数size指出一条记录的长度,而count指出要读或写多少条记录,这些记录在ptr所指的内存空间中连续存放,共占size * count个字节,fread从文件stream中读出size * count个字节保存到buffer中,而fwrite把buffer中的size,count个字节写到文件stream中。
头文件
#include<stdio.h>
返回值
返回值:读或写的记录数,成功时返回的记录数等于count,出错或读到文件末尾时返回的记录
数小于count,也可能返回0。
说明
例:
例1:fwrite
/****************fwrite*******************/
#include <stdio.h>
#include <stdlib.h>
struct record {
char name[10];
int age;
};
int main(void)
{
struct record array[2] = {{"Ken", 24}, {"Knuth", 28}};
FILE *fp = fopen("recfile", "w");
if (fp == NULL) {
perror("Open file recfile");
exit(1);
}
fwrite(array, sizeof(struct record), 2, fp);
fclose(fp);
return 0;
}
例2:fread
/*****************fread*********************/
#include <stdio.h>
#include <stdlib.h>
struct record {
char name[10];
int age;
};
int main(void)
{
struct record array[2];
FILE *fp = fopen("recfile", "r");
if (fp == NULL) {
perror("Open file recfile");
exit(1);
}
fread(array, sizeof(struct record), 2, fp);
printf("Name1: %s\tAge1: %d\n", array[0].name, array[0].age);
printf("Name2: %s\tAge2: %d\n", array[1].name, array[1].age);
fclose(fp);
return 0;
}
例3:将一个字符串写入文件:
char *str="hello,I am a test program!"; fwrite(str,sizeof(char),strlen(str),fp)
例4:将一个字符数组写入文件:
char str[]={'a','b','c','d','e'};
fwrite(str,sizeof(char),sizeof(str),fp)
3.将一个整型数组写入文件:
int a[]={12,33,23,24,12};
fwrite(a,sizeof(int),nmemb,fp);
注: