为什么这个程序不起作用? (将文件内容复制到另一个文件的程序)

时间:2015-11-24 06:45:38

标签: c++ turbo-c++

对于noob问题,我很抱歉,我是C ++的新手。我正在尝试编写一个程序,将文件逐行复制到另一个文件。这不是抛出任何错误,它正在运行,但它没有创建目标文件。

让我知道错误的位置..

#include <iostream>
#include <fstream>
using namespace std;

int main(int argc, char *argv[]) {
  ifstream fin;
  ofstream fout;
  char line[255];

  if (argc < 3) {
    cout << "ERROR - Incorrect number of arguments" << endl;
  } else {
    if (std::ifstream(argv[1])) {
      if (std::ifstream(argv[2])) {
        cout << "ERROR - Destination file already exists" << endl;
      } else {
        fin.open(argv[1], ios::in);
        fin.open(argv[2], ios::out);

        while(fin >> line) {
          cout << line << endl;
          fout << line << endl;
        }

        fin.close();
        fout.close();
      }
    } else {
      cout << "ERROR - Source file does not exist" << endl;
    }

  }

  return 0;  
}

更新:我将其更改为

后,我开始工作了
ifstream fin(argv[1]);
ofstream fout(argv[2]);

但它的复制很奇怪。它没有复制整行,它的复制如下:

#include
<iostream>
#include
<fstream>
using
namespace
std;
int
main(int
argc,
char
*argv[])
{
string
line;
if
(argc
<
3)
{
cout
<<
"ERROR
-
Incorrect
number
of
arguments"
<<
endl;
}
else
{
if
(std::ifstream(argv[1]))
{
if
(std::ifstream(argv[2]))
{
cout
<<
"ERROR
-
Destination
file
already
exists"
<<
endl;
}
else
{
ifstream
fin(argv[1]);
ofstream
fout(argv[2]);
while(fin
>>
line)
{
cout
<<
line
<<
endl;
fout
<<
line
<<
endl;
}
fin.close();
fout.close();
}
}
else
{
cout
<<
"ERROR
-
Source
file
does
not
exist"
<<
endl;
}
}
return
0;
}

我如何才能复制包括空格,并将整行视为整行?

更新:搞定了:

while(getline(fin, line)) {
  cout << line << endl;
  fout << line << endl;
}

1 个答案:

答案 0 :(得分:1)

fin.open(argv[2], ios::out);更改为fout.open(argv[2], ios::out);