FILE * fopen(const char * path,const char * mode);
返回值
path
mode
size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream);
size_t fwrite(const void *ptr, size_t size, size_t nmemb,FILE *stream);
返回值
ptr
size
nmemb
PS:尽量将size大小写为最小值(1字节)
int fclose(FILE *stream);
示例1:
#include<string.h>
#include<stdio.h>
int main(void)
{
FILE *fp = NULL;
const char *buf = "0123456789";
fp = fopen("DUMMY.FIL","w");/*创建一个包含10个字节的文件*/
fwrite(buf,strlen(buf),1,fp);/*将buf内容写入到文件中*/
fclose(fp);/*关闭文件*/return 0;
}
int fseek(FILE *stream, long offset, int fromwhere);
返回值
offset
Fromwhere
示例2-读写十六进制:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc,char* argv[])
{
FILE *fp = NULL;
int readbuf;
int readEnd;
int writebuf=100;
int len;
fp = fopen("./1.txt","rb+");
printf("read 1.txt: fp==NULL=%d size=%d\n",fp == NULL,sizeof(readbuf));
if(fp!=NULL) //打开成功,读数据
{
len=fread(&readbuf,sizeof(int),1,fp);
printf("read len=%d data=%d\n",len,readbuf);
fseek(fp,-sizeof(int),SEEK_END);
fread(&readEnd,sizeof(int),1,fp);
printf("read file end =%d\n",readEnd);
fclose(fp);
}
else //打开失败,则创建文件
{
fp = fopen("./1.txt","wb+");
printf("write 1.txt: fp==NULL=%d size=%d\n",fp == NULL,sizeof(readbuf));
if(fp!=NULL)
{
len=fwrite(&writebuf,sizeof(int),1,fp);
printf("write len=%d \n",len);
fclose(fp);
}
}
return 0;
}
运行第一次:
运行第二次
如果在嵌入式linux中,则有可能在写数据后强制关电,此时数据还在缓冲区,并没写到flash中,所以需要在fclose()前面加上:
fflush(fp); //会把缓冲区中的文件写到文件系统中
fsync(fileno(fp)); //同步数据到flash
fclose(fp);