Re: [问题] C的结构问题

楼主: overhead (overhead)   2015-05-28 00:23:47
※ 引述《tarobear (塔落熊)》之铭言:
: 开发平台(Platform): (Ex: VC++, GCC, Linux, ...)
: C
: 问题(Question):
: 书本范例: 利用学生ID搜寻,找出学生的资料
: 喂入的资料(Input):
: #include<stdio.h>
: struct mydata
: {
: int id;
: char name[12];
: int score;
: }buffer;
: int main(void)
: {
: FILE *fptr;
: int idkey;
: printf("Input ID to search");
: scanf("%d",&idkey);
: fptr=fopen("c:\\c_prog\\abc.txt","r");
: if(fptr!=NULL)
: {
: while(!feof(fptr)&&(idkey!=buffer.id))
: {
: fread(&buffer,sizeof(buffer),1,fptr)
: if(buffer.id==idkey)
: {
: printf("Yes! You got it!\n");
: printf("Student's ID:%d\n",buffer.id);
: printf("Student's NEME:%s\n",buffer.name);
: printf("Student's score:%d\n",buffer.score);
: }
: }
: }
: ...
: ...(以下省略
: }
: 补充说明(Supplement):
: 程式打得有点多, 主要是想问为何 buffer.id 就可以找到资料
: 而不需要像 buffer[1].id 这样呢?
你的"buffer"可以看成是一个"struct mydata"的变量
既然你从头到尾没有把他宣告成array
又怎么需要用[1]呢?
另个问题是关于fread的用法
https://msdn.microsoft.com/zh-tw/library/kt0etdcs.aspx
参考msdn
The fread function reads up to count items of size bytes from the input
stream and stores them in buffer.
意思是说,实际执行一次fread,是会读第二跟第三个参数相乘的大小
以你的fread(&buffer,sizeof(buffer),1,fptr)为例
就是一次读sizeof(buffer)*1=sizeof(buffer)
再来,msdn说
The file pointer associated with stream (if there is one) is increased by the
number of bytes actually read.
意思是使用fread时,你丢进去的最后一个参数fptr会因为fread而往后移动
而移动的量就是你读的数量,也就是刚刚的sizeof(buffer)*1
初学者使用function时要注意
哪些参数是给此function了解你的设定(function只读不写该参数)
哪些参数原本是一个空值,你宣告好后设定为参数,function可以把该值设定
成他想告诉你的值(function只写不读该参数)
有些就像这次的fptr一样,function想知道内容,又会告诉你他操作后的结果
(function又读又写该参数)
参数要能被function改动,他必须至少是个指标,才能call by reference
所以非指标的参数,基本上就是function会读但不写的
但是这些参数到底怎么用,是由设计那个function的前人所决定
我们这些使用者必须跟着他的思维放入&操作正确的参数
所以用function之前要上网看过描述
推荐你看msdn
他会附上_In_ _Out_ 来描述这件事
https://msdn.microsoft.com/zh-tw/library/jj159525.aspx
这件事是我初学程式语言时最迷惑的事情,分享给你

Links booklink

Contact Us: admin [ a t ] ucptt.com