C++同時開啟多檔案的範例
#include <iostream>
#include <vector>
#include <fstream>
#include <string>
#include <sstream>
using namespace std;
int main(int argc, char** argv)
{
cout << argc << endl;
if (argc < 2)
{
cerr << "need parameters" << endl;
return -1;
}
ifstream in(argv[1]);
if (!in)
{
cerr << "cannot open input file" << endl;
return -1;
}
ofstream out[3];
if (argc > 4)
{
out[0].open(argv[2]);
out[1].open(argv[3]);
out[2].open(argv[4]);
}
else
{
out[0].open("col01.txt");
out[1].open("col02.txt");
out[2].open("col03.txt");
}
string strline;
int data;
while(getline(in, strline))
{
stringstream strin(strline);
for (int i=0 ; i<3 ; ++i)
{
strin >> data;
out[i] << data << endl;
}
}
for (int i=0 ; i<3 ; ++i)
{
out[i].flush();
out[i].close();
}
return 0;
}
#include <vector>
#include <fstream>
#include <string>
#include <sstream>
using namespace std;
int main(int argc, char** argv)
{
cout << argc << endl;
if (argc < 2)
{
cerr << "need parameters" << endl;
return -1;
}
ifstream in(argv[1]);
if (!in)
{
cerr << "cannot open input file" << endl;
return -1;
}
ofstream out[3];
if (argc > 4)
{
out[0].open(argv[2]);
out[1].open(argv[3]);
out[2].open(argv[4]);
}
else
{
out[0].open("col01.txt");
out[1].open("col02.txt");
out[2].open("col03.txt");
}
string strline;
int data;
while(getline(in, strline))
{
stringstream strin(strline);
for (int i=0 ; i<3 ; ++i)
{
strin >> data;
out[i] << data << endl;
}
}
for (int i=0 ; i<3 ; ++i)
{
out[i].flush();
out[i].close();
}
return 0;
}
留言