C语言之随机读写文件

版权声明:博客注明来源即可。 https://blog.csdn.net/u014027680/article/details/82695766

来源:我的博客站 OceanicKang |《C语言之随机读写文件》

###一、获取位置指示器

  • ftell(FILE *stream)
#include <stdio.h>
#include <stdlib.h>

int main(void)
{
	FILE *fp;
	
	if ((fp = fopen("./random.txt", "w")) == NULL) {
		
		perror("打开文件失败!");
		exit(EXIT_FAILURE);
		
	}
	
	printf("%ld\n", ftell(fp));
	
	fputc('O', fp);
	printf("%ld\n", ftell(fp));
	
	fputs("ceanicKang", fp);
	printf("%ld\n", ftell(fp));
	
	fclose(fp);
	
	return 0;
}

1.jpg


###二、初始化位置指示器

  • rewind(FILE *stream)

将位置指示器初始化后,后续的文件读写操作与所选文件读写类型一致(文件读写类型请看《C语言之文件操作》


###三、设置位置指示器

  • int fseek(FILE *stream, long int offset, int whence)
参数 含义
stream 该参数是一个FILE对象的指针,指定一个待操作的文件流
offset 指定从whence参数的位置起偏移多少个字节
whence 指定从开始偏移的位置,具体值见下

【whence 值】

  • SEEK_SET — 文件头
  • SEEK_CUR — 当前的读写位置
  • SEEK_END — 文件末尾

【返回值】

  • 如果该函数调用成功,返回值是0
  • 如果该函数调用失败,返回一个非0值
#include <stdio.h>
#include <stdlib.h>

#define MAX 3

struct Student
{
	char name[24];
	int num;
	float score;
};

int main(void)
{
	struct Student std[MAX];
	struct Student select;
	
	FILE *fp;
	
	if ((fp = fopen("./score.txt", "wb")) == NULL) {
		
		perror("打开文件失败!");
		exit(EXIT_FAILURE);
		
	}
	
	// 写入 *******************************/
	printf("请输入学生信息三条,格式为:姓名 学号 成绩\n");
	
	for(int i = 0; i < MAX; i++) {
		
		scanf("%s %d %f", std[i].name, &std[i].num, &std[i].score);
		
	}
	
	fwrite(std, sizeof(struct Student), MAX, fp);
	
	fclose(fp);
	
	// 读取第二条 *************************/
	if ((fp = fopen("./score.txt", "rb")) == NULL) {
		
		perror("打开文件失败!");
		exit(EXIT_FAILURE);
		
	}
	
	fseek(fp, 1 * sizeof(struct Student), SEEK_SET);
	fread(&select, sizeof(struct Student), 1, fp);
	
	printf("%s(%d)的成绩为:%.2f", select.name, select.num, select.score);
	
	fclose(fp);
	
	return 0;
}

2.jpg

猜你喜欢

转载自blog.csdn.net/u014027680/article/details/82695766
今日推荐