hello world

随笔 - 2, 文章 - 63, 评论 - 0, 引用 - 0
数据加载中……

文件读取

fseek

  函数名: fseek
  功 能: 重定位流上的文件指针
  用 法: int fseek(FILE *stream, long offset, int fromwhere);
  描 述: 函数设置文件指针stream的位置。如果执行成功,stream将指向以fromwhere为基准,偏移offset个字节的位置。如果执行失败(比如offset超过文件自身大小),则不改变stream指向的位置。
  返回值: 成功,返回0,否则返回其他值。
  程序例:
  #include <stdio.h>
  long filesize(FILE *stream);
  int main(void)
  {
  FILE *stream;
  stream = fopen("MYFILE.TXT", "w+");
  fprintf(stream, "This is a test");
  printf("Filesize of MYFILE.TXT is %ld bytes\n", filesize(stream));
  fclose(stream);
  return 0;
  }
  long filesize(FILE *stream)
  {
  long curpos, length;
  curpos = ftell(stream);
  fseek(stream, 0L, SEEK_END);
  length = ftell(stream);
  fseek(stream, curpos, SEEK_SET);
  return length;
  }
  int fseek( FILE *stream, long offset, int origin );
  第一个参数stream为文件指针
  第二个参数offset为偏移量,整数表示正向偏移,负数表示负向偏移
  第三个参数origin设定从文件的哪里开始偏移,可能取值为:SEEK_CUR、 SEEK_END 或 SEEK_SET
  SEEK_CUR: 当前位置
  SEEK_END: 文件结尾
  SEEK_SET: 文件开头
  其中SEEK_CUR,SEEK_END和SEEK_SET依次为1,2和0。

fread

  C语言库函数名: fread
  功 能: 从一个流中读数据
  函数原型: int fread(void *ptr, int size, int nitems, FILE *stream);
  参 数:用于接收数据的地址(字符型指针)(ptr)
  单个元素的大小(size)
  元素个数(nitems)
  提供数据的文件指针(stream)
  返回值:成功读取的元素个数
  程序例:
  #include <string.h>
  #include <stdio.h>
  int main(void)
  {
  FILE *stream;
  char msg[] = "this is a test";
  char buf[20];
  if ((stream = fopen("DUMMY.FIL", "w+"))
  == NULL)
  {
  fprintf(stderr,
  "Cannot open output file.\n");
  return 1;
  }
  /* write some data to the file */
  fwrite(msg, strlen(msg)+1, 1, stream);
  /* seek to the beginning of the file */
  fseek(stream, 0, SEEK_SET);
  /* read the data and display it */
  fread(buf, strlen(msg)+1, 1,stream);
  printf("%s\n", buf);
  fclose(stream);
  return 0;
  }

posted on 2009-03-23 21:08 听风 阅读(180) 评论(0)  编辑  收藏 所属分类: C++


只有注册用户登录后才能发表评论。


网站导航: