file.seekg(pos);//set the file pointer to the start of the line to be deleted
}
//Not first line
else{
while(i++
if(!file.eof())
file.getline(buff,100);
pos=file.tellg();
if(!file.eof())
file.getline(buff,100);
len=file.tellg()-pos;//work out the length of the line we want to delete
file.seekg(pos);//set the file pointer to the start of the line to be deleted
}
}
k=len;
//Note: we assume there is not '\r' before '\n', it's depend on the write format of you .
if(strlen(pReplace)
printf("Error:new line must be longer than or equal to the original line\n");
return ;
}
file.write(pReplace,k-2);
file.close();
}
好了,下面我们来进行测试:
把第一行替换成eeeee,第二行替换成f,注意此时由于f只有一个字符,所以根据宁长勿短原则,我们应该补上n个空格,在replaceLine 内部会自动截取原行长度个字符的,然后我们删除第三行。
void main(){
//Create a file
ofstream out("now.txt");
out<<"aaaaa\n"<<"bbbbb\n"<<"ccccc\n"<<"ddddd\n";
out.close();
//Replace the first line
char *pReplace="eeeeeeeeeeeeeee";
replaceLine("now.txt",1,pReplace);
pReplace="f ";
replaceLine("now.txt",2,pReplace);
delLine("now.txt",3);
ifstream in("now.txt");
cout<
输出结果是:
eeeee
f
ddddd
摘自 不在浮沙筑高台