c - 为什么 fseek 在这里不返回位置,而只是将 fread 重定向到特定记录?
问题描述
所以我基本上有一个包含一些学生及其信息的二进制输入文件夹。在“while”函数之后,我不明白关于 fseek 和 fread 的一些事情。在我运行它并键入一个键来搜索学生之后,它会打印与该键关联的学生,而不是该位置上的那个(以字节为单位的维度作为偏移量)。我想知道为什么,为了将这些信息用于我的项目,因为这个程序是教授的一种教程。先感谢您!
*编辑(第二个程序是我对该项目的尝试,但使用汽车。它的输出是位置“chooseKey”的汽车,而不是作为第一个程序的“chooseKey”作为属性。我不知道我做错了什么.)
#include <stdio.h>
#include <conio.h>
typedef struct {
int nrm;
char CNP[14];
char nume[30];
int an;
int grupa;
unsigned char note[20];
char is;
} STUDENT;
int filesize(FILE* f, int rec_size)
{
long crt_pos;
int size;
crt_pos = ftell(f);
fseek(f, 0, SEEK_END) ;
size=ftell(f) / rec_size;
fseek(f, crt_pos, SEEK_SET);
return size;
}
void main()
{ char numefr[30] = "Studenti_r_f.dat";
FILE* f;
STUDENT x;
int key, dim;
fopen_s(&f, numefr, "rb+");
dim=filesize(f, sizeof(STUDENT));
printf_s("Enrollment number: ");
scanf_s("%d", &key);
while(key != 0)
{
//check key range
if(key >= dim)
printf_s("\nThere is no student with this enrollment number. Try again?");
else
{
//check if valid key
fseek(f, key*sizeof(STUDENT), SEEK_SET);
fread(&x, sizeof(STUDENT), 1, f);
if(x.is == 0)
printf("\nThere is no student with this enrollment number. Try again?");
else
printf_s("\nStudent: %s, Year: %d, Group: %d, ATP grade: %d\n",x.nume,x.an,x.grupa,x.note[5]);
}
printf_s("\n\nEnrollment number (or 0): ");
scanf_s("%d", &key);
}
fclose(f);
printf("\nDone. Press a key.",numefr);
_getch();
}
typedef struct {
int key;
char color[20];
int price;
char brand[15];
}CAR ;
int sizeOfFile(FILE* inBinFile, int sizeOfRecord)
{
long currentPosition;
int size;
currentPosition = ftell(inBinFile);
fseek(inBinFile, 0, SEEK_END);
size = ftell(inBinFile) / sizeOfRecord;
fseek(inBinFile, currentPosition, SEEK_SET);
return size;
}
void main()
{
FILE * inBinFile;
CAR var;
int chooseKey, fileDim;
printf_s("Type a key to identify a car..."); // 20 records in the file
scanf_s("%d", &chooseKey);
fopen_s(&inBinFile, "Machines.bin", "rb+");
fileDim = sizeOfFile(inBinFile, sizeof(CAR));
while (chooseKey != -1)
{
if (chooseKey >= fileDim)
printf_s("\nNo car with key %d found. Retry.", chooseKey);
else
{
fseek(inBinFile, chooseKey*sizeof(CAR), SEEK_SET);
fread(&var, sizeof(CAR), 1, inBinFile);
printf_s("\nThe %d key indicates to the %s car coloured in %s which cost %d dollars", chooseKey, var.brand, var.color, var.price);
}
printf_s("\n\n\nTo search for another car enter a key, or hit 1 and enter to stop: ");
scanf("%d", &chooseKey);
}
fclose(inBinFile);
printf_s("\nAlright. Press any key...");
_getch();
} ```
解决方案
推荐阅读
- javascript - 如何获取内联 css 溢出-y:自动效果的 Scrolltop() 值
- android - EditText 用于带小数位和后缀的数字
- java - onBackPressed 和调用刷新函数android
- excel - 将数字转换为单词 - 在两者之间添加“和”
- java - 无法找到具有路径的平台 SDK:平台;android-P
- svn - 检索最新的 SVN 提交是否需要用户名和密码?
- python - TypeError:float() 参数必须是字符串或数字,而不是“IntVar”
- php - @yield 如何变成价值?
- javascript - 从 web_accessible_resources 中列出的 javascript 文件访问 chrome 存储 API
- python - Python - var = var = var 值