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);
}
这是在已有原文件的基础上的代码。