1. fseek(), 用来移动文件流的读写位置
1-1. int fseek(FILE * stream, long offset, int whence)
whence 取值:
SEEK_SET: 文件开头 + offset (字节)
SEEK_CUR: 当前位置 + offset (字节), offset 可以负值
SEEK_END: 文件末尾 + offset (字节), offset 可以负值
1-2. 调用成功时则返回 0, 错误返回 -1, errno 存放错误代码
2. ftell(), 用来取得文件流目前的读写位置
2-1. long ftell(FILE * stream)
2-2. 调用成功返回目前的读写位置, 错误返回 -1, errno 会存放错误代码
3. 限制文件的大小只能在 long 类型的表示范围以内, 只能处理 2,000,000,000 (2G) 字节文件
#include <stdio.h>
#include <stdlib.h>
#define SLEN 50
int main(int argc, char *argv[])
{
char file[SLEN];
char ch;
FILE *fp;
long count, last;
puts("Enter the name of the file to be processed: ");
gets(file);
if((fp = fopen(file, "rb")) == NULL)
{
printf("can't open %s\n", file);
exit(EXIT_FAILURE);
}
fseek(fp, 0L, SEEK_SET); /* 移动到开头 */
last = ftell(fp);
printf("fseek(fp, 0L, SEEK_SET) , fteel(p): %ld\n", last);
fseek(fp, 0L, SEEK_END); /* 移动到结尾 */
last = ftell(fp);
printf("fseek(fp, 0L, SEEK_END) , fteel(p): %ld\n", last);
for(count = 1L; count <= last; count++)
{
fseek(fp, -count, SEEK_END);
ch = getc(fp);
if(ch != EOF)
putchar(ch);
}
putchar('\n');
fclose(fp);
return EXIT_SUCCESS;
}
1-1. int fseek(FILE * stream, long offset, int whence)
whence 取值:
SEEK_SET: 文件开头 + offset (字节)
SEEK_CUR: 当前位置 + offset (字节), offset 可以负值
SEEK_END: 文件末尾 + offset (字节), offset 可以负值
1-2. 调用成功时则返回 0, 错误返回 -1, errno 存放错误代码
2. ftell(), 用来取得文件流目前的读写位置
2-1. long ftell(FILE * stream)
2-2. 调用成功返回目前的读写位置, 错误返回 -1, errno 会存放错误代码
3. 限制文件的大小只能在 long 类型的表示范围以内, 只能处理 2,000,000,000 (2G) 字节文件
#include <stdio.h>
#include <stdlib.h>
#define SLEN 50
int main(int argc, char *argv[])
{
char file[SLEN];
char ch;
FILE *fp;
long count, last;
puts("Enter the name of the file to be processed: ");
gets(file);
if((fp = fopen(file, "rb")) == NULL)
{
printf("can't open %s\n", file);
exit(EXIT_FAILURE);
}
fseek(fp, 0L, SEEK_SET); /* 移动到开头 */
last = ftell(fp);
printf("fseek(fp, 0L, SEEK_SET) , fteel(p): %ld\n", last);
fseek(fp, 0L, SEEK_END); /* 移动到结尾 */
last = ftell(fp);
printf("fseek(fp, 0L, SEEK_END) , fteel(p): %ld\n", last);
for(count = 1L; count <= last; count++)
{
fseek(fp, -count, SEEK_END);
ch = getc(fp);
if(ch != EOF)
putchar(ch);
}
putchar('\n');
fclose(fp);
return EXIT_SUCCESS;
}
0 件のコメント:
コメントを投稿