Freopen多文件输入-C++

Freopen Multiple File input - C++

本文关键字:-C++ 输入 文件 Freopen      更新时间:2023-10-16

我试过这个

...
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",有人能帮我吗?

您是用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…)混合使用

我强烈建议你花几个小时阅读更多的文档(在没有阅读文档的情况下,不要使用任何标题、函数或类型)和书籍。你的代码太糟糕了。

因此,您可以在C:中进行编码

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

但这在第二次迭代中不起作用(因为第一次调用freopen时已经关闭了stdin),所以您确实希望使用fopen,而不是freopen,并从inf文件中读取。不要忘记在for循环体的末尾使用fclose

顺便说一句,如果你用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++11与C99不同),并阅读更多文档。此外,在启用所有警告和调试信息的情况下进行编译(例如,如果使用GCC,则针对C++11代码的g++ -std=c++11 -Wall -g或针对C99代码的gcc -std=c99 -Wall -g),并且使用调试器

正如前面提到的解决方案一样,freopen一次只能用于一个文件。因此,为了绕过C++中的文件IO,我会查看这个源代码并使用fstreams:https://www.bgsu.edu/arts-and-sciences/computer-science/cs-documentation/reading-data-from-files-using-c-plus-plus.html

打开多个文件的一个示例方法是

int a, b;
in.open("file1"); 
in >> a;
in.close();
in.open("file2");
in >> b;
in.close();