Monday, December 4, 2017

C++17(C11): Bounds-checking fopen_s() and freopen_s()

C++17 added the bounds-checking functions fopen_s() and freopen_s().

#include <cstdio>
#include <iostream>
using namespace std;

int main()
{
  FILE    * fp1  ;
  FILE    * fp2  ;
  errno_t   errno;
  char      line[10];

  errno = fopen_s(&fp1, "test.txt", "w");
  cout << errno << " ";
  fprintf_s(fp1, "Hello");

  errno = freopen_s(&fp2, "test.txt", "r", fp1);
  cout << errno << " ";
  fscanf_s(fp2, "%s", line, sizeof(line));
  printf(line);

  cout << endl;
  return 0;
}
// Output: 0 0 Hello
References:
http://en.cppreference.com/w/c/io/fopen
http://en.cppreference.com/w/c/io/freopen
http://en.cppreference.com/w/c/io/fscanf

No comments:

Post a Comment