Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

c

What is freopen_s in C?

Behzad Ahmad

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

We use the freopen_s function to close a file with the oldstream and reassign the new stream to a file specified by the file name.

Syntax

errno_t freopen_s(
   FILE ** stream,
   const char * fileName,
   const char * mode,
   FILE* oldStream
);

Parameters

stream - Points to the reopened stream.

fileName - Name of the file to reopen.

mode - The mode for the reopened stream.

oldStream - The stream to reopen .

Modes

r: To read the file.

w: Opens an empty file for writing.

a: Used to open the file in append mode.

r+ Opens for both reading and writing.

w+ Opens an empty file for reading and writing.

a+ Opens the file for reading and appending.

Return value

The function returns 0 if executed successfully.

The function returns an error code if an error occurs.

Code

#include<iostream>
using namespace std;
FILE *stream;
int main()
{
int a, b;
freopen_s(&stream, "in.txt", "r", stdin); //opens the file in read only mode
freopen_s(&stream, "out.txt", "w", stdout); //opens file in writing mode
scanf("%d %d", &a, &b); //Input 2 values
printf("%d %d", a, b); //print values
fclose(stdin); //close file
fclose(stdout); //close file
return 0;
}

RELATED TAGS

c

CONTRIBUTOR

Behzad Ahmad
Copyright ©2022 Educative, Inc. All rights reserved

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring