首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >C++文件重定向

C++文件重定向
EN

Stack Overflow用户
提问于 2013-08-06 13:25:30
回答 4查看 34.8K关注 0票数 16

为了获得更快的输入,我看到您可以执行file-redirection,并包含一个已经设置了cin输入的文件。

从理论上讲,它的使用应如下所示:

代码语言:javascript
复制
App.exe inputfile outputfile

据我从C++入门书中了解到,下面的C++ code1应该读取文本文件中的cin输入,而不需要任何其他特殊指示like2

2

代码语言:javascript
复制
include <fstream>
ofstream myfile;
myfile.open ();

1以下C++代码..。

代码语言:javascript
复制
#include <iostream>
int main()
{
    int val;
    std::cin >> val; //this value should be read automatically for inputfile
    std::cout << val;
    return 0;
}

我是不是遗漏了什么?

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2013-08-06 13:28:25

要使用代码1,您必须像这样调用您的程序:

代码语言:javascript
复制
App.exe < inputfile > outputfile

您还可以使用:

代码语言:javascript
复制
App.exe < inputfile >> outputfile

在这种情况下,输出不会用命令的每次运行来重写,但是输出将被附加到已经存在的文件中。

有关在Windows中重定向输入和输出的更多信息,您可以找到这里

请注意,<>>>符号将逐字输入--它们不只是用于本解释中的表示目的。因此,例如:

代码语言:javascript
复制
App.exe < file1 >> file2
票数 22
EN

Stack Overflow用户

发布于 2013-08-06 13:54:04

除了原来的重定向,>/ >><

您也可以重定向std::cinstd::cout

如下所示:

代码语言:javascript
复制
int main()
{
    // Save original std::cin, std::cout
    std::streambuf *coutbuf = std::cout.rdbuf();
    std::streambuf *cinbuf = std::cin.rdbuf(); 

    std::ofstream out("outfile.txt");
    std::ifstream in("infile.txt");

    //Read from infile.txt using std::cin
    std::cin.rdbuf(in.rdbuf());

    //Write to outfile.txt through std::cout 
    std::cout.rdbuf(out.rdbuf());   

    std::string test;
    std::cin >> test;           //from infile.txt
    std::cout << test << "  "; //to outfile.txt

    //Restore back.
    std::cin.rdbuf(cinbuf);   
    std::cout.rdbuf(coutbuf); 

}
票数 5
EN

Stack Overflow用户

发布于 2013-08-06 14:13:21

我只是在解释有关的命令行参数。

您可以将文件名作为命令行输入提供给可执行文件,但随后需要在代码中打开它们。

喜欢

您提供了两个命令行参数,即inputfile & outputfile。

App.exe inputfile outputfile

现在在你的代码中

代码语言:javascript
复制
#include<iostream>
#include<fstream>
#include<string>

int main(int argc, char * argv[])
{
   //argv[0] := A.exe
   //argv[1] := inputFile
   //argv[2] := outputFile

   std::ifstream vInFile(argv[1],std::ios::in); 
   // notice I have given first command line argument as file name

   std::ofstream vOutFile(argv[2],std::ios::out | std::ios::app);
   // notice I have given second command line argument as file name

   if (vInFile.is_open())
   {
     std::string line;

     getline (vInFile,line); //Fixing it as per the comment made by MSalters

     while ( vInFile.good() )
     {
         vOutFile << line << std::endl;
         getline (vInFile,line);          
     }
     vInFile.close();
     vOutFile.close();
  }

  else std::cout << "Unable to open file";

  return 0;
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/18081565

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档