Change a text file in random access
I have a Text file and want to Change it in some places for example in
4030 t0 4060, in this way :if there is a character 'C' or 'c' followed by
'G' or 'g' ,must be changed in 'B' character ,the input file is a text
file and i want to get a changed text output file , there is no random
access in text file and must open file in binary form and make changes but
the output file will be binary and i dont have any idea to get a text
output .the codes are in below:
int main()
{
string str,cstr;
ReadTextFile("in",4030,4060);
return 0;
}
string ReadTextFile(string path, int from, int to)
{
fstream fp(path.c_str(),ios::in|ios::out| ios::binary);
char * target;
string res,str;
target = new char[to - from + 1];
if (!target)
{
cout << "Cannot allocate memory." << endl;
return "";
}
fp.seekg(from);
fp.read(target, to - from);
target[to - from] = 0;
res = target;
str=changestring(res);
fp.seekg(from);
fp.write((char *)&str,to-from);
return res;
}
string changestring(string str)
{
int l=str.length();
l=l-1;
for(int i=0;i<= l;i++)
{
if(str[i]=='C' || str[i]=='c')
{
int j=i+1;
if(str[j]=='G' || str[j]=='g')
str[i]='B';
}
}
return str;
}
No comments:
Post a Comment