How to use the freopen_s function

To read the 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 pretty well.

However, in visual studio, the compiler gives me an error due to freopen and suggests that I use freopen_s instead. I am trying to understand how the freopen_s function works, but I cannot. My code is:

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 a “pause” does not work. CMD disappears immediately after the program ends without printing. I do not know why the "stream" is used in freopen_s. Thanks for answering my question.

+4
source share
2 answers

- C IOSTREAM. . , "std::string" .

int main() 
{

std::string  file =  "input.txt";
std::string line;
std::ifstream  text_filestream(file.c_str());

while(std::getline(text_filestream, line)) {
 std::cout<<line<<std::endl;
 }
}    
-2

. freopen, "-D_CRT_SECURE_NO_WARNINGS" , .

VS -

Project- > "Project" Properties → C/++ → Command Line → ( ).

!

+2

Source: https://habr.com/ru/post/1529021/


All Articles