string - C++ editing text file using ofstream -
i trying manipulate text of text file (without using vectors):
(this assignment engineering paper, , i'm not allowed use vectors)
variable numrows can integer (i chose 3 example) , square matrix of elements in output text file 'example.txt'
here code:
#include <iostream> #include <fstream> using namespace std; int main () { int numrows = 3; ofstream myfile ("example.txt"); if (myfile.is_open()) { (int = 0; < numrows; i++) { (int j = 0; j < numrows; j++) { myfile << "test\t"; } myfile << "\n"; } myfile.close(); } else cout << "unable open file"; return 0; }
the text file follows:
test test test test test test test test test
my question is, once i've done of - how open again , edit it? eg. wanted edit row 2, column 2 "hello":
test test test test hello test test test test
how this? need able manipulate strings stored in text file , unsure of since have separated each string tab character
thank taking time help!
on typical file systems can't insert characters @ arbitrary posistions. if want "edit" file in-place you'd use format each record takes fixed amount of space. of course, size of each record bounded size of fixed amount. example use 10 bytes per record, limiting maximum size 10. if record shorter you'd either pad out byte can't happen (e.g., tabs) or use suitable number of bytes @ fixed location of record specify size if used string. 255 bytes 1 byte used.
since records have fixed size seek location of modified record: start (row * columns + column) * record_size
. you'd write new value (and if choose save size, size of string in record).
if need support variable length strings without upper bound or need use compact representatio above approach doesn't work. you'll need entirely rewrite file. you'd
- open input file reading.
- open temporary file writing.
- read each unchanged record prio chang , write temporary file.
- read changed record , nothing it.
- write new value temporary file.
- copy remainder of input file temporary file.
- close both files.
- rename temporary file source file name.
obviously, if need multiple edits @ time continue copying/replacing needed. approach stay pretty same, though.
i write code homework assignment above removed thinking said assignment. also, don't need practice programming i'll skip providing code.
Comments
Post a Comment