【问题标题】:What is stdin and how is it being used with fscanf?什么是标准输入以及它如何与 fscanf 一起使用?
【发布时间】:2023-04-07 11:52:01
【问题描述】:

我不明白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 接受输入并将 no 放入 sturct 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;

}

【问题讨论】:

  • 这个问题似乎是两个(不相关的?)问题。

标签: c file stdin scanf randomaccessfile


【解决方案1】:
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 会发生什么?
  • fseek 用于移动 FILE* 位置,因此如果您不使用 fseek,则输出变为 Fseek Hello World.no
【解决方案2】:

来自文档 (man scanf):

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

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

来自文档 (man stdin)

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

所以

scanf( ...

其实等价于

fscanf(stdin, ...

【讨论】:

    猜你喜欢
    • 2010-12-25
    • 2010-12-09
    • 2016-09-10
    • 1970-01-01
    • 1970-01-01
    • 2014-02-12
    • 1970-01-01
    • 1970-01-01
    • 2012-04-16
    相关资源
    最近更新 更多