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

  1. open input file reading.
  2. open temporary file writing.
  3. read each unchanged record prio chang , write temporary file.
  4. read changed record , nothing it.
  5. write new value temporary file.
  6. copy remainder of input file temporary file.
  7. close both files.
  8. 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

Popular posts from this blog

dns - How To Use Custom Nameserver On Free Cloudflare? -

python - Pygame screen.blit not working -

c# - Web API response xml language -