FILE *fp = NULL;
char line[1024] = {0};
fp = fopen("20200922_1622.csv", "r+");
if( NULL == fp ) {
printf("Fail to open file!\n");
return 0;
}
do
{
memset(line, 0, sizeof(line));
line = fgets(line, 1024, fp);
if (NULL == line) {
printf("get line is null\n");
break;
}
printf("line is:%s \n", line);
if(line[0] == '#') {
continue ;
}
}while(tmp != NULL );//逐行读取数据
if( NULL == fp ) {
printf("fp is null!\n");
} else {
fclose(fp);
fp = NULL;
}
头文件:#include <stdio.h>
定义函数:int fseek(FILE * stream, long offset, int whence);
参数 whence 为下列其中一种:
- SEEK_SET 参数offset 即为新的读写位置.
- SEEK_CUR 以目前的读写位置往后增加offset 个位移量.
- SEEK_END 将读写位置指向文件尾后再增加offset 个位移量. 当whence 值为SEEK_CUR 或
- SEEK_END 时, 参数offet 允许负值的出现.
举例:
fseek(fp, 0L, SEEK_SET); //定位至文件开始处
fseek(fp, 10L, SEEK_SET); //定位至文件中的第10个字节
fseek(fp, 2L, SEEK_CUR); //从文件当前位置前移2个字节
fseek(fp, 0L, SEEK_END); //定位至文件结尾
fseek(fp, -10, SEEK_END); //从文件结尾处回退10个字节
定义函数:long ftell(FILE * stream);
ftell()函数返回指定流的当前文件指针的位置。
示例代码:
long getfilelength(FILE *fp)
{
long curpos=0L;
long length=0L;
curpos = ftell(fp);
fseek(fp, 0L, SEEK_END);
length = ftell(fp);
fseek(fp, curpos, SEEK_SET);
return length;
}
本文详细介绍了使用C语言进行文件操作的方法,包括如何打开、读取、定位文件指针及获取文件长度等基本操作。通过具体示例展示了fgets、fseek和ftell等函数的应用场景。
1003

被折叠的 条评论
为什么被折叠?



