首页 > 解决方案 > 我不能在 VS2019 中使用“fscanf”

问题描述

你好

我在 DEVC++ 中使用了 "fscanf(f,"%d",&a)" 它仍然有效。但是我在VS2019中写了“fscanf”并报错。

标签: visual-studio-2015

解决方案


不要使用 fscanf 它是不安全的,不应再使用,使用 fscanf_s。C 是一门古老的语言,因此它有很多不应该使用且无法删除的内容。

https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/fscanf-s-fscanf-sl-fwscanf-s-fwscanf-sl?view=vs-2017

// crt_fscanf_s.c
// This program writes formatted
// data to a file. It then uses fscanf to
// read the various data back from the file.

#include <stdio.h>
#include <stdlib.h>

FILE *stream;

int main( void )
{
   long l;
   float fp;
   char s[81];
   char c;

   errno_t err = fopen_s( &stream, "fscanf.out", "w+" );
   if( err )
      printf_s( "The file fscanf.out was not opened\n" );
   else
   {
      fprintf_s( stream, "%s %ld %f%c", "a-string",
               65000, 3.14159, 'x' );
      // Set pointer to beginning of file:
      fseek( stream, 0L, SEEK_SET );

      // Read data back from file:
      fscanf_s( stream, "%s", s, _countof(s) );
      fscanf_s( stream, "%ld", &l );

      fscanf_s( stream, "%f", &fp );
      fscanf_s( stream, "%c", &c, 1 );

      // Output data read:
      printf( "%s\n", s );
      printf( "%ld\n", l );
      printf( "%f\n", fp );
      printf( "%c\n", c );

      fclose( stream );
   }
}

推荐阅读