🍓个人主页:bit.. 

🍒系列专栏:Linux(Ubuntu)入门必看   C语言刷题 

目录

4. 文件的顺序读写

4.1 对比一组函数:

5. 文件的随机读写

5.1 fseek

5.2 ftell

 5.3 rewind


4. 文件的顺序读写

C语言——文件操作(中)_开发语言

4.1 对比一组函数:

scanf/fscanf/sscanf

rintf/fprintf/sprintf 

5. 文件的随机读写

5.1 fseek

根据文件指针的位置和偏移量来定位文件指针。

int fseek ( FILE * stream, long int offset, int origin );

例子: 

/* fseek example */
#include <stdio.h>
int main ()
{
  FILE * pFile;
  pFile = fopen ( "example.txt" , "wb" );
  fputs ( "This is an apple." , pFile );
  fseek ( pFile , 9 , SEEK_SET );
  fputs ( " sam" , pFile );
  fclose ( pFile );
  return 0;
}

5.2 ftell

返回文件指针相对于起始位置的偏移量

long int ftell ( FILE * stream );

例子:

/* ftell example : getting size of a file */
#include <stdio.h>
int main ()
{
  FILE * pFile;
  long size;
  pFile = fopen ("myfile.txt","rb");
  if (pFile==NULL) perror ("Error opening file");
  else
 {
    fseek (pFile, 0, SEEK_END);   // non-portable
    size=ftell (pFile);
    fclose (pFile);
    printf ("Size of myfile.txt: %ld bytes.\n",size);
 }
  return 0;
}

 5.3 rewind

让文件指针的位置回到文件的起始位置

void rewind ( FILE * stream );

例子:

/* rewind example */
#include <stdio.h>
int main ()
{
  int n;
  FILE * pFile;
  char buffer [27];
  pFile = fopen ("myfile.txt","w+");
  for ( n='A' ; n<='Z' ; n++)
    fputc ( n, pFile);
  rewind (pFile);
  fread (buffer,1,26,pFile);
  fclose (pFile);
  buffer[26]='\0';
  puts (buffer);
  return 0;
}