第一个案例
#include <stdio.h>
#include <string.h>int main()
{FILE *fp;char c[] = "Thisisrunoob1";char buffer[20];/* 打开文件用于读写 */fp = fopen("C:/Users/ACER/Desktop/rr.txt", "w+"); /* 写入数据到文件 */fwrite(c, strlen(c), 1, fp); //从c中读取 ( strlen(c) * 1 )个字符 写入到fp流中/* 查找文件的开头 */fseek(fp, 1, SEEK_SET); //把位置指针移动到离文件开头 1 个字节处,也就是开头/* 读取并显示数据 */fread(buffer, 2, 3, fp); //从buffer里读取2 * 3 个字节printf("%s\n", buffer);fclose(fp);return(0);
}
long ftell(FILE *stream);
参数 stream 指向对应的文件,函数调用成功将返回当前读写位置相对于文件首的偏移量;调用失败将返回 -1 ,并会设置 errno 以指示错误原因
#include <stdio.h>
#include <stdlib.h>int main(void)
{FILE *fp = NULL;int ret;/* 打开文件 */if (NULL == (fp = fopen("test.txt", "r"))){perror("fopen error");exit(-1);}printf("文件打开成功!\n");/* 将读写位置移动到文件末尾 */if (0 > fseek(fp, 0, SEEK_END)){perror("fseek error");fclose(fp);exit(-1);}/* 获取当前位置偏移量 */if (0 > (ret = ftell(fp))){perror("ftell error");fclose(fp);exit(-1);}printf("文件大小: %d 个字节\n", ret);/* 关闭文件 */fclose(fp);exit(0);
}
FR:徐海涛(hunkxu)