Home > database >  C - my program stops running `freopen` function from <cstdio>
C - my program stops running `freopen` function from <cstdio>

Time:12-09

In my main.cpp:


#include <cstdio>
#include "hashtable.h"

int main() {
    printf("1hello");
    freopen("2.txt", "w", stdout);
    printf("2hello");
    freopen("1.txt", "r", stdin);
    printf("3hello");
    int type;
    char buffer[1000];int data;
    hashtable table(10000, new naive_hashing(), new linear_probe());
    while (true) {
        scanf("%d", &type);
        if (type == 0) {
            scanf("%s", buffer);scanf("%d", &data);
            table.insert(hash_entry(buffer, data));
        }
        else if (type == 1) {
            scanf("%s", buffer);
            printf("%d\n", table.query(buffer));
        }
        else break;
    }
    return 0;
}

1.txt:

0 dhu_try 3039
0 shirin 3024
0 SiamakDeCode 2647
0 huanghansheng 233
1 dhu
1 dhu_try
1 shirin
1 siamakdecode0
1 huanghansheng
2

output:

1hello

As you can see the program paused after it entered the first freopen function. I have checked the document already and still yet cannot find the reason why it stopped running. Can anyone help me please? :pleading_face:

CodePudding user response:

You redirected all output to stdout to the file 2.txt when you did

freopen("2.txt", "w", stdout);

That's why no printf outputs are shown on the console after that freopen. Look in the file 2.txt and you will most probably see the output there - if the freopen succeeded. Always check if functions that can fail have succeeded.

  • Related