Editing a text file

Hi everyone,

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.


Thanks.
Last edited on
The File Format Should Be Like This.....
You Should Write A file Like This...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
24        Salman         88   98   97   99   99   96.2  A  


33        Onaib          89   90   99   99   95   94.4  B  

60        Abubaker       87   89   99   99   97   94.2  B  

69        KakaMessi      89   90   91   92   93   91    B  


9         Akash          98   97   94   93   92   94.8  B  

21        Kashif         76   75   74   73   72   74    F  

354       RaybalAkhtar   98   97   96   96   76   92.6  B  

660       Lakri          78   75   67   89   91   80    D  

780       Pepsi          89   90   91   92   93   91    B  




1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
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 ;
		 	
	}
}
Thank you very much for your contribution, there are some functions which are new for me, but i'll manage to work it out.
Topic archived. No new replies allowed.