Freopen多文件输入 - C ++

时间:2014-09-13 06:32:00

标签: c++ freopen

我试过这个

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

是一个字符“doc1.txt”,“doc2.txt”,...

但是,这段代码只打开“doc1.txt”,有人可以帮帮我吗?

1 个答案:

答案 0 :(得分:-1)

您使用C语言编写还是使用C ++编写代码?你必须选择!

您应该阅读freopen(3)的文档并使用其结果。

   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.

此外,您不应将C ++ I / O流(例如std::cin>>)与C文件混合使用(例如stdinfscanf ...)。< / p>

我强烈建议您花几个小时阅读更多文档(不要使用任何标题,功能或类型而不阅读其文档)和书籍。你的代码是可怜的。

所以你可以在 C 中编码:

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

但是在第二次迭代中不会工作(因为stdin已经被freopen的第一次调用关闭了),所以你真的想要使用fopen,而不是freopen并从该inf文件中读取。不要忘记在fclose循环体的末尾for

顺便说一句,如果你用C ++编写代码(你必须在C和C ++之间选择,它们是不同的语言),你只需使用std::ifstream,也许就像

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

最后,选择您编码的语言和标准(C++11C99不同)并阅读更多文档。此外,编译时启用所有警告和调试信息(例如,对于C ++ 11代码为g++ -std=c++11 -Wall -g或对于C99代码为gcc -std=c99 -Wall -g,如果使用GCC)并且使用调试器