fewind()
函数名: rewind()
用 法: void rewind(FILE *stream);
头文件:
stdio.h
返回值:无
举例
//以数据块的形式对文件的操作
int file_option_block()
{
FILE *fp;
char strTextGets1[20] = {"aaaaadasdsd"};
char strTextGets2[20] = {"12345678912"};
char strTextBuff[50] = {0};
int iwr_cnt = 0;
int file_option_block()
{
FILE *fp;
char strTextGets1[20] = {"aaaaadasdsd"};
char strTextGets2[20] = {"12345678912"};
char strTextBuff[50] = {0};
int iwr_cnt = 0;
if(NULL == (fp = fopen("X:\\FileTest\\filetext","w+")))
{
printf("创建文件失败!\n");
}
else
{
printf("创建文件成功!\n");
}
fputs(strTextGets1,fp);
iwr_cnt = fwrite(strTextGets2,sizeof(strTextGets2),1,fp);
printf("写入成功的数据块个数为:%d\n",iwr_cnt);
{
printf("创建文件失败!\n");
}
else
{
printf("创建文件成功!\n");
}
fputs(strTextGets1,fp);
iwr_cnt = fwrite(strTextGets2,sizeof(strTextGets2),1,fp);
printf("写入成功的数据块个数为:%d\n",iwr_cnt);
//将文件的位置指针设置到文件的开头
rewind(fp);
while(0 == feof(fp))
{
fread(strTextBuff,20,1,fp);
printf("读取到的数据块内容是:%s\n",strTextBuff);
}
{
fread(strTextBuff,20,1,fp);
printf("读取到的数据块内容是:%s\n",strTextBuff);
}
fclose(fp);
}
}
ftell()
函数名
ftell
ftell函数原型
long
ftell
(FILE *stream);
ftell函数功能
使用fseek函数后再调用函数ftell()就能非常容易地确定文件的当前位置。
ftell约束条件
因为ftell返回long型,根据long型的取值范围-2
31
~2
31
-1(-2147483648~2147483647),故对大于2.1G的文件进行操作时出错。
ftell(fp);
利用函数 ftell() 也能方便地知道一个文件的长。如以下语句序列: fseek(fp, 0L,SEEK_END); len =ftell(fp); 首先将文件的当前位置移到文件的末尾,然后调用函数ftell()获得当前位置相对于文件首的位移,该位移值等于文件所含字节数。
举例1:
1
2
3
4
5
6
7
8
9
10
11
|
#include <stdio.h>
int
main(
void
)
{
FILE
*stream;
stream =
fopen
(
"MYFILE.TXT"
,
"w+"
);
fprintf
(stream,
"This is a test"
);
printf
("The file pointer is at byte \
%ld\n",
ftell
(stream));
fclose
(stream);
return
0;
}
|
举例2:
ftell一般用于读取文件的长度,下面补充一个例子,读取文本文件中的内容:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
|
#include <stdio.h>
#include <stdlib.h>
int
main()
{
FILE
*fp;
int
flen;
char
*p;
/* 以只读方式打开文件 */
if
((fp =
fopen
(
"1.txt"
,
"r"
))==NULL)
{
printf
(
"\nfile open error\n"
);
exit
(0);
}
fseek
(fp,0L,SEEK_END);
/* 定位到文件末尾 */
flen=
ftell
(fp);
/* 得到文件大小 */
p=(
char
*)
malloc
(flen+1);
/* 根据文件大小动态分配内存空间 */
if
(p==NULL)
{
fclose
(fp);
return
0;
}
fseek
(fp,0L,SEEK_SET);
/* 定位到文件开头 */
fread
(p,flen,1,fp);
/* 一次性读取全部文件内容 */
p[flen]=
'\0'
;
/* 字符串结束标志 */
printf
(
"%s"
,p);
fclose
(fp);
free
(p);
return
0;
}
|
程序改进
1
2
3
4
5
6
7
8
9
10
11
|
#include <stdio.h>
main()
{
FILE
*myf;
long
f1;
//此处将f1设置为long 可以读取更长的文件
myf=
fopen
(
"1.txt"
,
"rb"
);
fseek
(myf,0,SEEK_END);
f1=
ftell
(myf);
fclose
(myf);
printf
(“%d\n”,f1);
}
|