转自:http://hi.baidu.com/wengjiang000/item/867ead5da7d95c10abf6d736
通常文件打开后,读写位置按先后顺序.但有时你想变动读写位置,例如重新从某处起,再读一次.
功 能: 将文件指针重新指向一个流的开头
用 法: int rewind(FILE *stream);函数原型: long ftell(FILE *fp)
函数功能:得到流式文件的当前读写位置,其返回值是当前读写位置偏离文件头部的字节数.
fread
功 能: 从一个流中读数据
函数原型: size_tfread(void*buffer,size_tsize,size_tcount,FILE*stream);
参 数:
1.用于接收数据的地址(指针)(buffer)
2.单个元素的大小(size) :单位是字节而不是位,例如读取一个整型数就是2个字节
3.元素个数(count)
4.提供数据的文件指针(stream)
返回值:成功读取的元素个数 程序例 #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;
}