您的位置:首页 > 编程语言 > C语言/C++

【C++练习】文件合并程序

2017-07-28 17:03 246 查看

代码:

#include
#include
#include
#include
#include

int main(int argc,char* argv[])
{
std::string Name1st, Name2nd;
if (3 != argc)
{
std::cout << "Input the first file name : \n";
std::cin >> Name1st;
std::cout << "Input the second file name : \n";
std::cin >> Name2nd;
}
else
{
Name1st = argv[1];
Name2nd = argv[2];
}

std::ofstream fout;
std::ifstream fin1st, fin2nd;

fin1st.open(Name1st.c_str(), std::ios_base::in | std::ios_base::binary);

if (fin1st.is_open())
std::cout << "Successfully open " << Name1st << std::endl;
else
{
std::cerr << "Error in opening " << Name1st << std::endl;
std::cin.get();
std::cin.get();
std::exit(EXIT_FAILURE);
}

fin2nd.open(Name2nd.c_str(), std::ios_base::in | std::ios_base::binary);

if (fin2nd.is_open())
std::cout << "Successfully open " << Name2nd << std::endl;
else
{
fin1st.close();
std::cerr << "Error in opening " << Name2nd << std::endl;
std::cin.get();
std::cin.get();
std::exit(EXIT_FAILURE);
}

int n;
if ((n = Name1st.find_first_of('.')) != std::string::npos)
Name1st.erase(Name1st.begin() + n, Name1st.end());
if ((n = Name2nd.find_first_of('.')) != std::string::npos)
Name2nd.erase(Name2nd.begin() + n, Name2nd.end());

std::ostringstream FinalName;
FinalName << Name1st << "and" << Name2nd;

fout.open(FinalName.str(), std::ios_base::out | std::ios_base::trunc | std::ios_base::binary);

if (fout.is_open())
std::cout << "Successfully create " << FinalName.str() << std::endl;
else
{
fin1st.close();
fin2nd.close();
std::cerr << "Error in creating " << FinalName.str() << std::endl;
std::cin.get();
std::cin.get();
std::exit(EXIT_FAILURE);
}

char szTmp[50];

while (fin1st.read(szTmp, sizeof szTmp))
fout.write(szTmp, sizeof szTmp);
fout.write(szTmp, fin1st.gcount());

while (fin2nd.read(szTmp, sizeof szTmp))
fout.write(szTmp, sizeof szTmp);
fout.write(szTmp, fin2nd.gcount());

std::cout << "Done\n";

fout.close();
fin2nd.close();
fin1st.close();
std::cin.get();
std::cin.get();
return 0;
}

分析:

char szTmp[50];

while (fin1st.read(szTmp, sizeof szTmp))
fout.write(szTmp, sizeof szTmp);
fout.write(szTmp, fin1st.gcount());

while (fin2nd.read(szTmp, sizeof szTmp))
fout.write(szTmp, sizeof szTmp);
fout.write(szTmp, fin2nd.gcount());

以上代码循环读取和写入文件

改进:

可将以上代码改进为:

fout << fin1st.rdbuf()<<fin2nd.rdbuf();
fin.rdbuf()返回指向文件缓冲区的指针(类型:streambuf *),可用于将缓冲区中所有数据输出
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  c++
相关文章推荐