什么是标准输入(stdin),它如何与fscanf一起使用?

3
我不理解stdin和fscanf之间的联系。
struct musteri{
    int no;
    char name[40];
    char surname[25];
    double arrear;

};



 int main() {

    struct musteri hesapBilgi={0,"","",0.0};

    FILE *ptr;
    if((ptr=fopen("eleman.txt","r+"))==NULL){
        printf("error");
    }

    else{
        printf("\n enter a no if you want exit enter 0 -->");   
        scanf("%d",&hesapBilgi.no); 

scanf接收一个输入并将其放入结构体musteri中

while(hesapBilgi.hesapno !=0){


            printf("enter a surname name and arrear --->"); 
            fscanf(stdin,"%s%s%lf",hesapBilgi.surname,hesapBilgi.name,&hesapBilgi.arrear);

在这里,fscanf是从文件中读取数据吗?还是其他事情正在进行?
        fseek(ptr,(hesapBilgi.no-1)*,sizeof(struct musteri),SEEK_SET); 

fseek() 函数是用于移动文件指针到指定位置的函数。
        fwrite(&hesapBilgi,sizeof(struct musteri),1,ptr);

        printf("enter a no :");
        scanf("%d",&hesapBilgi.no);


    }
    fclose(ptr);
}


return 0;

}


这个问题似乎是两个(不相关的?)问题。 - alk
2个回答

8

从文档(man scanf)中可以得知:

scanf() 函数从标准输入流 stdin 读取输入,fscanf([FILE * stream, ...]) 从流指针 stream 读取输入 [...]

stdin 是一个 FILE*。它是一个输入流。

从文档(man stdin)中可以得知:

在正常情况下,每个 UNIX 程序在启动时都有三个流打开,一个用于输入,一个用于输出,一个用于打印诊断或错误消息。这些通常连接到用户的终端 [...]

因此,

scanf( ...

实际上等同于

fscanf(stdin, ...

0
int fscanf ( FILE * stream, const char * format, ... );

它从流中读取格式化输入。

stdin是标准输入流。

fseek用于将与流相关联的位置指示器设置为新位置。

SEEK_SET是一个标志,用于从文件开头设置位置。

fseek的示例:

#include <stdio.h>

int main ()
{
  FILE * pFile;
  pFile = fopen ( "example.txt" , "wb" );
  fputs ( "Fseek Hello World." , pFile );
  fseek ( pFile , 9 , SEEK_SET );
  fputs ( "no" , pFile );
  fclose ( pFile );
  return 0;
}

输出:Fseek Helno World


为什么我们需要在上面的例子中使用fseek?如果我们不使用fseek会发生什么? - Emrah
fseek 用于移动 FILE* 的位置,如果您没有使用 fseek,则输出将变为 Fseek Hello World.no。 - developer.ahm

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接