c语言fwrite和fread连续读写文件流

c语言fwrite和fread连续读写文件流

本例程的编写是基于windows,编译器用的是gnu下的gcc:

  • 头文件stdio.h和stdlib.h
  • 读写函数是fwrite和fread
  • 文件指针移动函数有lseek,ftell,fseek
  • *文件结束判断函数feof
  • 函数的具体参数和返回值可查阅手册

连续写入long类型的一个数组


#include 
#include 
int main(int argc, char const *argv[])
{

    unsigned long buffer[]={10011,120000,130000,140000,500000,90000,1000000};
    FILE *fp;
    long *fpos=buffer;//连续读取时,需要改变数组的地址,数组的常量指针buffer运算时有问题,所以申请了一个long指针。
    int num=0;//统计写入的数据块
    int nn=0;//写入时返回的数据块
    int n=sizeof(buffer)/sizeof(long);
    if ((fp=fopen("myfile.bin","wb+"))==NULL)
    {
        printf("%s\n","can not open file");
        exit(0);
    }


    while(n--)
    {
     printf("position=%d\n",ftell(fp) );
     printf("buffer[i]=%d\n",*fpos );
     printf("fpos=%0x\n",fpos );    
     nn=fwrite(fpos,sizeof(long),1,fp);
     fpos=fpos+1;//注意:读取玩一个数据后,需要将指针移动到下一个地址
     num=num+nn;

    }
    printf("position=%d\n",ftell(fp) );
    printf("%d\n",num );
    fclose(fp);
    return 0;

myfile.bin如下:

1b27 0000 c0d4 0100 d0fb 0100 e022 0200
20a1 0700 905f 0100 4042 0f00

连续读取myfile.bin

#include 
#include 
int main(int argc, char const *argv[])
{
    unsigned long buffer[7];/*这里其实可以动态申请内存*/
    long *fpos=buffer;

    int i=0;
    int num=0;
    FILE *fp;
    if ((fp=fopen("myfile.bin","rb+"))==NULL)
    {
        printf("%s\n","can not open file");
        exit(0);
    }
    while(!feof(fp))/*判断是否结束,这里会有个文件结束符*/
    {
     fread(fpos,sizeof(long),1,fp);
     num++;
     fpos++;

    }   
    for ( i = 0; i < num-1; ++i)/*因为有文件结束符,所以将读取的数据减一*/
    {
        printf("%d\n",*(fpos-num+i));
        /*这里用数组也可以 printf("%d\n",buffer[i]*/        
    }
    fclose(fp);
    return 0;
}

c读取文件的函数很多,fgetc,fgets,fscanf,sscanf.


你可能感兴趣的:(c)