对于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;
}
答案 0 :(得分:1)
将fin.open(argv[2], ios::out);
更改为fout.open(argv[2], ios::out);