c++freopen

Freopen Multiple File input - C++


I have tried this

...
for(int i=0;i<totalDoc;i++){
        freopen(name[i],"r",stdin);
        while(cin>>s!=NULL){doc[i]=doc[i]+s+" ";}
        fclose(stdin);
        ...
}

with name is a char "doc1.txt", "doc2.txt", ...

but, this code only open "doc1.txt", can somebody help me please?


Solution

  • Are you coding in C or in C++ ? You have to choose!

    You should read the documentation of freopen(3) and use its result.

       The freopen() function opens the file whose name is the string
       pointed to by path and associates the stream pointed to by stream
       with it.  The original stream (if it exists) is closed.
    

    Also, you should not mix C++ I/O streams (e.g. std::cin and >>) with C files (e.g. stdin and fscanf...).

    I strongly suggest you to spend several hours reading more documentation (don't use any header, function or type without having read its documentation) and books. Your code is pityful.

    So you might code in C :

    for(int i=0;i<totalDoc;i++){
       FILE*inf = freopen(name[i],"r",stdin); // wrong
       if (!inf) { perror(name[i]); exit(EXIT_FAILURE); }
    

    but that won't work on the second iteration (since stdin has been closed by the first call to freopen), so you really want to use fopen, not freopen and read from that inf file. Don't forget to fclose it at the end of your for loop body.

    BTW, if you code in C++ (and you have to choose between C and C++, they are different languages) you would simply use an std::ifstream, perhaps like

    for(int i=0;i<totalDoc;i++){
       std::ifstream ins(name[i]);
       while (ins.good()) {
         std::string s;
         ins >> s;
         doc[i] += s + " ";
       };
    }
    

    At last, choose which language and which standard you code in (C++11 is different of C99) and read more documentation. Also, compile with all warnings and debug info enabled (e.g. g++ -std=c++11 -Wall -g for C++11 code or gcc -std=c99 -Wall -g for C99 code, if using GCC) and use the debugger.