人无完人,持之以恒,方能见真我!!!
共同进步!!
文章目录
一、文件的随机读取函数
1.fseek函数
int fseek ( FILE * stream, long int offset, int origin );
a | bcde
abc | de
#include <stdio.h>
int main()
{
FILE* pf = fopen("test.txt", "w");
if (pf == NULL)
{
perror("fopen");
return 1;
}
fputs("This is an apple.", pf);
fseek(pf, 9, SEEK_SET);
fputs(" orange", pf);
fclose(pf);
pf = NULL;
return 0;
}
This is a|n apple.
2.ftell函数
long int ftell ( FILE * stream );
#include <stdio.h>
int main()
{
long size;
FILE* pf = fopen("test.txt", "r");
if (pf == NULL)
{
perror("fopen");
return 1;
}
fseek(pf, 0, SEEK_END);
size = ftell(pf);
fclose(pf);
printf("Size of test.txt: %ld bytes.\n", size);
pf = NULL;
return 0;
}
3.rewind函数
void rewind ( FILE * stream );
#include <stdio.h>
int main()
{
int i;
char buffer[27];
FILE* pf = fopen("test.txt", "w+");
if (pf == NULL)
{
perror("fopen");
return 1;
}
for (i = 'A'; i <= 'Z'; i++)
{
fputc(n, pf);
}
rewind(pf);
fread(buffer, 1, 26, pf);
fclose(pf);
pf = NULL;
buffer[26] = '\0';
printf(buffer);
return 0;
}
二、文件读取结束的判断
1.被错误使用的feof
2.判断文件读取结束的方法
3.判断文件结束的原因
feof
int feof ( FILE * stream );
ferror
int ferror ( FILE * stream );
判断文件读取结束原因示例
#include <stdio.h>
int main()
{
char arr[20];
FILE* pf = fopen("test.txt", "r");
if (pf == NULL)
{
perror("fopen");
return 1;
}
fgets(arr, 20, pf);
printf("%s\n", arr);
if (feof(pf))
{
printf("文件正常读取结束\n");
}
if (ferror(pf))
{
printf("文件错误读取结束\n");
perror("读取失败原因");
}
fclose(pf);
pf = NULL;
return 0;
}