简体   繁体   English

使用I / O流从一个文件读取并写入另一个文件

[英]Using I/O streams to read from one file and write to another

I'm going through a text-book where an exercise entails copying text from one file and write it's lower-case equivalent to another file. 我正在阅读一本教科书,其中的练习需要从一个文件中复制文本,并将其写成与另一文件小写等效。 I can't seem to find a way to do that using just I/O streams (most of the solutions I found online use stream buffers). 我似乎找不到仅使用I / O流来做到这一点的方法(我在网上找到的大多数解决方案都使用流缓冲区)。

My code is this 我的代码是这样

int main()
{
string f_name1, f_name2;
cout << "enter the file names" << '\n';

cin >> f_name1>>f_name2;
ofstream fs{ f_name1 };
ifstream fsi{f_name1};
ofstream fs2{f_name2};

fs << "LoRem ipSUM teXt TaXi";

char ch;

while (fsi.get(ch)) {


    fs2 << ch;
}

After running nothing is written to the second file (f_name2). 运行后,没有任何内容写入第二个文件(f_name2)。 It's just a blank file. 这只是一个空白文件。

Edit: 编辑:

This doesn't work either 这也不起作用

int main()
{
string f_name1, f_name2;
cout << "enter the file names" << '\n';

cin >> f_name1>>f_name2;
ofstream fs{ f_name1 };
ifstream fsi{f_name1};
ofstream fs2{f_name2};

fs << "LoRem ipSUM teXt TaXi";

char ch;

while (fsi>>ch) {


    fs2 << ch;
}

}
  1. You are complicating your task for no apparent gain. 您正在使任务复杂化,而没有明显的收获。 There is no need for 不需要

     ofstream fs{ f_name1 }; fs << "LoRem ipSUM teXt TaXi"; 
  2. Use a text editor and create the contents of the input file outside the program. 使用文本编辑器并在程序外部创建输入文件的内容。

Here's an updated version of your main fuction: 这是您的main功能的更新版本:

int main()
{
   string f_name1, f_name2;
   cout << "enter the file names" << '\n';

   cin >> f_name1 >> f_name2;

   ifstream fs1{f_name1};
   if ( !fs1 )
   {
      std::cerr << "Unable to open " << f_name1 << " to read from.\n";
      return EXIT_FAILURE;
   }

   ofstream fs2{f_name2};
   if ( !fs2 )
   {
      std::cerr << "Unable to open " << f_name2 << " to write to.\n";
      return EXIT_FAILURE;
   }

   // Using ostream::put() seems the right function to use
   // for writing when you are using istream::getc() for reading.
   char ch;
   while (fs1.get(ch))
   {
      fs2.put(std::tolower(ch));
   }
}

Hmm. 嗯。 So you're writing to the file and then reading the contents and writing out again. 因此,您正在写入文件,然后读取内容并再次写出。 Okay... 好的...

You might need to fs.flush() after the fs << code. 您可能需要在fs <<代码之后输入fs.flush()。 The data can be buffered, waiting for a newline character to trigger a flush, or doing one yourself. 可以对数据进行缓冲,等待换行符触发刷新,或者自己进行操作。

I'd also put in some print statements in your while loop to make sure you're getting what you think you're getting. 我还将在while循环中放入一些打印语句,以确保您得到的是您想得到的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM