The return value of freopen is null, so what is the cause?

Asked 2 years ago, Updated 2 years ago, 40 views

I did free-open, but I print out the NULL value. The standard input works well in the console window with a scanf after removing freopen, but what's the problem with continuing to print NULL values if I open it?

I'm not surePlease help me.


#include <stdio.h>
#pragma warning(disable:4996)

int main(void)
{
    int d[20];

    if (freopen("input.txt", "r", stdin) == NULL)
        fprintf(stderr, "error redirecting stdin\n");

    for (int i = 0; i < 20; i++){

        scanf("%d", &d[i]);

    }

    for (int i = 0; i < 20; i++){

        printf("%d ", d[i]);
    }

    printf("\n");

    return 0;
}

c

2022-09-22 19:42

1 Answers

freopen("input.txt", "r", stdin);

This code means replacing the standard input stream with a input.txt file. Therefore, there is no need to return a new file stream from the code above. stdin has changed.

So this code above

if (freopen("input.txt", "r", stdin) == NULL)
    fprintf(stderr, "error redirecting stdin\n");

Change it to this code.

freopen("input.txt", "r", stdin);
if (stdin == NULL)
    fprintf(stderr, "error redirecting stdin\n");


2022-09-22 19:42

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.