How do I edit a specific line of a text file in C++? Let’s say I want to open a file and change the focus or pointer or whatever its called to line 17 column 20. That way I can edit text after line 17, column 20.
I tried this, but it didnt work.
ofstream txtFile("textFile.txt");
fseek(txtFile, 17, 20);
txtFile << "New stuff to enter at this point (overwrites old not insert)";
How do I do this?
fseekis not seeking counting lines, but rather bytes. What you instruct the program is not to position the pointer at column 20 of 17th line, but rather at the 17 + 20 = 37th byte of the file.The first parameter of the function is the origin, i.e. the count of bytes from the origin from which you count, and the second – how many more you offset.
See the reference of
fseek.I am not aware of any library that can do byte positioning in respect of lines and columns in C++. You will probably need to use a higher level function and parse lines one by one (e.g. using
getlineif you are after C++ solution).