在保存C语言的代码文件时,如果你空埋第二个文件和第一个文件名重复,系统会提醒你已有该文件,是否覆盖,只有选择覆盖你才能让两个文件名一模一样,但是这样后面的文件就会把前面的仿亏饥文件内容覆盖掉。
C语言编译器普遍存在备返于各种不同的 *** 作系统中,其设计也影响了Java、Python等编程语言。
#include <iostream>#include <fstream>
#include <string>
using namespace std
const int BUF_LEN = 8096
int main() {
string src_name = "input.txt"
string ins_name = "output.txt"
long ins_pos = 10
getline(cin, src_name)
getline(cin, ins_name)
cin >>ins_pos
if (src_name.length() == 0 || ins_name.length() == 0 || ins_pos <0)
{cout <<"bad input!" <<endlreturn 1}
ifstream source(src_name.c_str())
if (!source) {
cout <<"file: " <<src_name <<endl
cout <<"open failed" <<endlreturn 1
}
ifstream insert(ins_name.c_str())
if (!insert) {
cout <<"file: " <<梁慧答 ins_name <<碧丛 endl
cout <<"open failed" <<endlreturn 1
}
source.seekg(0, ios::end)
int src_len = source.tellg()
source.seekg(0, ios::beg)
if (ins_pos >src_len) {
cout <<"bad insert position: " <<ins_pos <<endl
return 1
}
string tmp_name = src_name + ".tmp"
ofstream target(tmp_name.c_str())
if (!target) {
cout <<"橡慧file: " <<tmp_name <<endl
cout <<"open failed" <<endl
return 1
}
long count = ins_pos
char buffer[BUF_LEN]
while (!source.eof() &&count >BUF_LEN){
source.read(buffer, BUF_LEN)
target.write(buffer, BUF_LEN)
count -= BUF_LEN
}
source.read(buffer, count)
target.write(buffer, count)
insert.seekg(0, ios::end)
count = insert.tellg()
insert.seekg(0, ios::beg)
while (!insert.eof() &&count >BUF_LEN){
insert.read(buffer, BUF_LEN)
target.write(buffer, BUF_LEN)
count -= BUF_LEN
}
insert.read(buffer, count)
target.write(buffer, count)
count = src_len - ins_pos
while (!source.eof() &&count >BUF_LEN){
source.read(buffer, BUF_LEN)
target.write(buffer, BUF_LEN)
count -= BUF_LEN
}
source.read(buffer, count)
target.write(buffer, count)
source.close()
insert.close()
target.close()
if(remove(src_name.c_str())) {
cout <<"remove file failed" <<endl
}
if(rename(tmp_name.c_str(), src_name.c_str())) {
cout <<"rename file failed" <<endl
}
return 0
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)