Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use function freopen_s

In order to read input from a text file, I wrote the following code:

int main(){
    int x;
#ifndef ONLINE_JUDGE
    freopen("input.txt", "r", stdin);
#endif
    scanf("%d", &x);
    printf("%d\n", x);
    system("pause");
    return 0;
}

It works quite good.

However, in visual studio, the compiler gives me an error because of freopen and suggests me to use freopen_s instead. I try to understand how function freopen_s works, but I can't. My code:

int main(){
    int x;
#ifndef ONLINE_JUDGE
    FILE *stream;
    freopen_s(&stream, "input.txt", "r", stdin);
#endif
    scanf("%d", &x);
    printf("%d\n", x);
    system("pause");
    return 0;
}

It does not output anything, and even the "pause" does not work. The cmd disappears right after the program finishes without anything printed. I don't know why the "stream" is used in freopen_s. Thank you for answering my question.

like image 750
Michael Yeh Avatar asked Nov 26 '22 15:11

Michael Yeh


1 Answers

I would give you an alternate way. If you still want to use freopen, you can use "-D _CRT_SECURE_NO_WARNINGS" this option with the terminal command, the error message will be suppressed.

In VS you can add it under the following link -

Project-> "Project" Properties -> C/C++ -> Command Line -> Additional Options(Text box on bottom right).

This should resolve the issue!

like image 150
Karan Chopra Avatar answered Dec 09 '22 15:12

Karan Chopra