I want to edit a text file, but i'm stuck in finding the correct functions or methods to do so.
So far I'm able to open a text file and look for a certain Sting, but i have no idea on how to move the cursor, add or replace information, steps 4 - 7 in my pseudocode shown below.
Can you provide some guidance? Which functions should I use (in case they already exist)?
A sample 'easy' code would be appreciated as well.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
Pseudocode:
1. Open file.
2. While not eof
3. Read file until string "someString" is found.
4. Position the cursor at the next line (to where the someString was found).
5. If "someString" = A go to step 6. Else go to step 7.
6. Replace the information in whole line with "newString". Go to step 8.
7. Add new information "newString_2", without deleting the existing.
8. Save and close the text file.
void modify_student(int a )
{
fstream x( "C:/Users/MR_Salman/Desktop/new.txt",ios::out|ios::in|ios::binary );
while ( !x.eof() )
{
x >> s.roll_no ;
if ( s.roll_no==a )
{
int pos = x.tellg() ;
cout << "Enter Data R N P C M E CS PER GRADE \n\n" ;
getdata() ;
calculate();
ostringstream os ;
os << a ;
string sub = os.str() ;
int size = sub.length();
x.seekp(pos-size) ;
x << left ;
x <<setw(10)<< s.roll_no <<setw(15) << s.name << setw(5) << s.p_marks <<setw(5) << s.c_marks
<<setw(5)<< s.m_marks <<setw(5) << s.e_marks <<setw(5) << s.cs_marks << setw(6)<< s.per <<setw(3) << s.grade ;
x << "\n" ;
cout << "\t\t\tData is Modified \n\n\n" ;
x.close();
break ;
}
x >> s.name ;
x >> s.p_marks ;
x >> s.c_marks ;
x >> s.m_marks ;
x >> s.e_marks ;
x >> s.cs_marks ;
x >> s.per ;
x >> s.grade ;
}
}