fseek函数在操作文件中字符串和结构体时的不同

本文详细介绍了如何使用fseek函数在C语言中操作文本文件,包括对字符串数组和结构体数组的定位和读写,以及结构体文件的保存和显示。
摘要由CSDN通过智能技术生成

fseek函数在操作文件中字符串和结构体时的不同

用于字符串时的测试图

#include<stdio.h>
#include<math.h>
#include<string.h>
#include<stdlib.h>
int main()
{
	FILE* file;
	fopen_s(&file,"D:\\test.txt","rt");
	if (file == NULL)
	{
		printf("failed to open");
		exit(1);
	}
	//char str[] = "abcdef";
	//fputs(str,file);
	//fclose(file);
	fseek(file, 4, 0);
	char str1 [2] = {0};
	fgets(str1,2,file);
	/*char ch[1] = {0};
	
	fread(ch, 1, 1, file);
	*/
	printf("%s", str1);
    fclose(file);
	
}

在这里插入图片描述
用于结构体时的图片

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define LEN1 15  //表示学生学号、姓名、电话、性别的最大长度
#define LEN2 40  //表示学生住址和E-mail的最大长度



void newsave(int n);
void show(int n);



#define N 100   //最大的学生数量
int t = 1;  //n代表当前学生人数,t用于控制整个程序的执行以及程序的退出。
struct student
{
	char ID[15];
	char name[15];
	char sex[4];
	char year[16];
	char month[4];
	char day[4];
	char address[30];
	char telenum[15];
	char email[30];
}stu[100];




int main(int argc, char* argv[])
{
	int n;
	int i;
    printf("请输入你要添加的学生的个数:");

	scanf_s("%d",&n);
	/*for (i = 0; i < n; i++)
	{
		printf("请输入第%d个学生的学号:",i+1);
		scanf_s("%s",stu[i].ID,15);
		printf("请输入第%d个学生的姓名:", i + 1);
		scanf_s("%s", stu[i].name,15);
		printf("请输入第%d个学生的性别:", i + 1);
		scanf_s("%s", stu[i].sex,4);
		printf("请输入第%d个学生的出生年份:", i + 1);
    	scanf_s("%s", stu[i].year,16);
		printf("请输入第%d个学生的出生月份:", i + 1);
		scanf_s("%s", stu[i].month,4);
		printf("请输入第%d个学生的出生日期:", i + 1);
		scanf_s("%s", stu[i].day,4);
		printf("请输入第%d个学生的地址:", i + 1);
		scanf_s("%s", stu[i].address,30);
		printf("请输入第%d个学生的电话号码:", i + 1);
		scanf_s("%s", stu[i].telenum,15);
		printf("请输入第%d个学生的邮箱地址:", i + 1);
		scanf_s("%s", stu[i].email,30);
		newsave(n);
	}*/
	
	show(n);

	return 0;
}

void newsave(int n)
{
	int k;
	FILE* file;
	fopen_s(&file, "D:\\stuinfo.txt", "wt");
	if (file == NULL)
	{
		printf("无法打开文件!");
		exit(1);
	}
	for (k = 0; k < n; k++)
	{
		fwrite(&stu[k], sizeof(stu), 1, file);
		if (fwrite(&stu[k], sizeof(stu), 1, file) != 1)
		{
			printf("文件写入错误!");
			exit(0);
		}
	}
	fclose(file);
}
void show(int n)
{
	int i;
	FILE* file;
	fopen_s(&file, "D:\\stuinfo.txt", "rt");
	if (file == NULL)
	{
		printf("无法打开文件!");
		exit(1);
	}
	for (i = 0; i < n; i++)
	{
		rewind(file);
		fseek(file, (i+1) * sizeof(stu), 0);
		fread(&stu[i], sizeof(stu), 1, file);
		printf("%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s",stu[i].ID, stu[i].name, stu[i].sex, stu[i].year, stu[i].month, stu[i].day, stu[i].address, stu[i].telenum, stu[i].email);
		
		printf("\n");
	}
	free(file);
	fclose(file);
}

这是在已有原文件的基础上的代码。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值