Editing a text file - c++

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 string, 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.
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.

I would recommend to put the getline command into the while loop because then it won't stop only because of EOF but when getline is not able to read anymore.
Like when the error bad occurs (which happens when someone deleted the file while your program was reading it).
It seems like you want to search inside a string, so "find" might be quite helpful.
#include <iostream>
#include <fstream>
#include <string>
int main (){
std::fstream yourfile;
std::string line, someString;
yourfile.open("file.txt", ios::in | ios::app); //The path to your file goes here
if (yourfile.is_open()){ //You don't have to ask if the file is open but it's more secure
while (getline(line)){
if(line.find(someString) != string::npos){ //the find() documentation might be helpful if you don't understand
if(someString == "A"){
//code for replacing the line
}
else{
yourfile << "newString_2" << endl;
}
} //end if
} //end while
} //end if
else cerr << "Your file couldn't be opened";
yourfile.close();
return 0;
}
I can't tell you how to replace a single line in a text file but I hope you can work with that little I can give you.

This should be a good start:
// basic file operations
#include <string>
#include <fstream>
int main ()
{
std::fstream myfile;
std::string line;
while (!myfile.eof())
{
std::getline(myfile,line); // Check getline() doc, you can retrieve a line before/after a given string etc.
//if (line == something)
//{
// do stuff with line, like checking for content etc.
//}
}
myfile.close();
return 0;
}
More informations here

Related

Input Output with fstream

Can anyone tell me what is wrong with this code? I always get not open.
#include <iostream>
#include <fstream>
using namespace std;
int main(){
fstream fs;
fs.open("fsfile2",ios::in|ios::out|ios::binary);
if(fs.is_open()){
fs.write("wow",sizeof("wow"));
char str[20];
fs.read((char*)str,sizeof(str));
cout<<str<<endl;}
else
cout<<"Not open\n";
return 0;
}
Try this code
fs.open("fsfile2", ios::app|ios::in|ios::out|ios::binary);
By using the open() like you are that file will not be created if that is your goal.
If you want to create a new file please look at: fstream won't create a file
If the file exists, you are not looking for it in the right path. Or change the file name to the full path or put the executable in the folder where the file is.
Hope this helps.
Probably, you do not have permissions to create files in the directory, where your executable is.
Solution:
Please add a file extension to the filename.
If it's a text file, it will be
"fsfile2.txt"
Then, I tried removing
ios::in
since the first process only writes to file, and by removing that, the file is created and "wow" is also written at it.
In order for these lines
fs.read((char*)str,sizeof(str));
cout<<str<<endl;
to work,
You need to close the stream after writing to it, then open the stream in read mode, then read the contents. Take note that closing the stream will save the edited file.
Additional:
You can also change
fs.write("wow",sizeof("wow"));
to
fs << "wow";
You can do the same when reading from file,
fs >> str;
You can also use the string class of C++, instead of char array so that the number of characters inside the file won't be your problem anymore.
#include <string>
string str;
Checking for EOF (end-of-file) is recommended since files are read line by line. Once you add a new line and add a character to the line, the code that doesn't loop until EOF will only read the first line of the file.
In order to solve this, it is recommended to loop until EOF is reached.
while(!fs.eof()) {
fs >> str;
cout << str << endl;
}
So here is the improved snippet:
#include <string>
fs.open("fsfile2.txt", ios::out); // ios::out for write only
if(fs.is_open()) {
// writes "wow" to file
fs << "wow";
// closes the file
fs.close();
// ios::in for read only
fs.open("fsfile2.txt", ios::in);
// better to define variable just before using it
string str;
// loops until end-of-file
while(!fs.eof()) {
// reads a line from file, stores it to str
fs >> str;
// shows str to screen
cout << str << endl;
}
}
*Note: I removed
ios::binary
Since your code is not dealing with binary files yet.
I tried these and it worked fine! Have a nice day!
fstream fs; does not create a new file for you.
You need to make sure that the file exists in your project directory.
On the other hand, if you were to use ofstream fs("file.txt"); it would create the file for you. Or use only ios::out when you open fstream fs, this will create the file for you.

Replace line in txt file c++

I just wondering cause i have a text file containing STATUS:USERID:PASSWORD in accounts.txt
example it would look like this:
OPEN:bob:askmehere:
OPEN:john:askmethere:
LOCK:rob:robmypurse:
i have a user input in my main as such user can login 3x else status will change from OPEN to LOCK
example after 3 tries of john
before:
OPEN:bob:askmehere:
OPEN:john:askmethere:
LOCK:rob:robmypurse:
after:
OPEN:bob:askmehere:
LOCK:john:askmethere:
LOCK:rob:robmypurse:
what i have done is:
void lockUser(Accounts& in){
// Accounts class consist 3 attributes (string userid, string pass, status)
ofstream oFile;
fstream iFile;
string openFile="accounts.txt";
string status, userid, garbage;
Accounts toupdate;
oFile.open(openFile);
iFile.open(openFile);
while(!iFile.eof()){
getline(iFile, status, ':');
getline(iFile, userid, ':');
getline(iFile, garbage, '\n');
if(userid == in.getUserId()){
toupdate.setUserId(in.getuserId());
toupdate.setPassword(in.getPassword());
toupdate.setStatus("LOCK");
break;
}
//here i should update the account.txt how do i do that?
ofile.open(openFile);
ofile<<toupdate.getStatus()<<":"<<toupdate.getUserId()":"<<toupdate.getPassword()<<":"<<endl;
}
There are two common ways to replace or otherwise modify a file. The first and the "classic" way is to read the file, line by line, check for the line(s) that needs to be modified, and write to a temporary file. When you reach the end of the input file you close it, and rename the temporary file as the input file.
The other common way is when the file is relatively small, or you have a lot of memory, is to read it all into memory, do the modification needed, and then write out the contents of the memory to the file. How to store it in memory can be different, like a vector containing lines from the file, or a vector (or other buffer) containing all characters from the file without separation.
Your implementation is flawed because you open the output file (which is the same as the input file) inside the loop. The first problem with this is that the operating system may not allow you to open a file for writing if you already have it open for reading, and as you don't check for failure from opening the files you will not know about this. Another problem is if the operating system allows it, then your call to open will truncate the existing file, causing you to loose all but the very first line.
Simple pseudo-ish code to explain
std::ifstream input_file("your_file");
std::vector<std::string> lines;
std::string input;
while (std::getline(input_file, input))
lines.push_back(input);
for (auto& line : lines)
{
if (line_needs_to_be_modified(line))
modify_line_as_needed(line);
}
input_file.close();
std::ofstream output_file("your_file");
for (auto const& line : lines)
output_file << line << '\n';
Use ReadLine and find the line you wanna replace, and use replace to replace the thing you wanna replace. For example write:
string Example = "Text to find";
openFile="C:\\accounts.txt"; // the path of the file
ReadFile(openFile, Example);
OR
#include <fstream>
#include <iostream>
#include <string>
int main() {
ifstream openFile;
string ExampleText = BOB;
openFile("accounts.txt");
openFile >> ExampleText;
openFile.replace(Example, "Hello");
}

using ios::ate over-write data

My task is to write in a precise position into file.txt with C++
And because my file is static ( it will not be changed) I decided to count the position of curseur where I have to write. ( I know it isn't the best idea to di this)
This is my file and I have to write after '=' :
It is clear that I want to over-write "null;"
But I don't understand why "int main" in the otehr line is also over-writed! Have a look to the following please to undersatnd my problem:
My questions are the following:
How Can I avoid this?
Have you other idea to achieve the goal as described above ?
The is my attempt :
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
ofstream monFlux("client.txt",ios::in | ios::ate);
if(monFlux)
{
monFlux.seekp(61, ios::beg);
int position = monFlux.tellp();
monFlux<< "DECryptBlockWithPCRYPT(d);";
}
else
{
cout << "ERROR" << endl;
}
system("pause");
return 0;
}
First, it looks like you're opening an output stream for reading (ios::in) is that correct?
I don't think you can insert characters the way you describe.
Your approach is more like a human would do it in a text editor. The stream object on the other side just gives you access to the bytes on the disk. It has no "select and replace" text function.
I think this approach could work:
Open an input stream for reading the file and an output stream for writing one.
Stream the first N characters directly to the output stream.
Skip the "null" and insert your replacement string.
Stream the rest of the input file into the output stream.
On success, replace the original file with the new one.

C++ File not read?

I want to read a file line by line. Did something like
void Parse (string filepath) {
ifstream sourceFile;
sourceFile.open(filepath);
for (string line; getline(sourceFile, line);) {
cout << "1" << endl;
cout << line << endl;
}
}
int main() {
Parse("C:\\test.txt");
getchar();
return 0;
}
Then put some text into C:\test.txt, but when I run, I dont get anything. Why? Not even the "1". I notice no exception if the file is not there too. I suppose that a sign of a problem?
You have to check for success/error manually. Try with ifstream::good():
sourceFile.open(filepath);
if(!sourceFile.good()) {
// do something
If you don't want to check manually, you can enable exceptions:
// call that before open()
sourceFile.exceptions ( ifstream::failbit | ifstream::badbit );
I think you have problems opening the file. I would suggest two things:
check if sourceFile is opened successfully(if (sourceFile))
debug the code and see the code path your code follows.
EDIT: adding the actual solution to the problem in my answer(instead of just a comment) so that people won't miss it:
Here is one more thought - check the file name in its properties. Has happened to me that if windows hides the extension of the file the name is actually test.txt.txt, while what I see displayed is only test.txt.
change your for loop to
for (string line; sourceFile.good();) {
getline(sourceFile, line);
}
This way, you check the validity of your stream in the conditional part of the for, and get the line if the stream good.

getline() returns empty line in Eclipse but working properly in Dev C++

Here is my code:
#include <iostream>
#include <stdlib.h>
#include <fstream>
using namespace std;
int main() {
string line;
ifstream inputFile;
inputFile.open("input.txt");
do {
getline(inputFile, line);
cout << line << endl;
} while (line != "0");
return 0;
}
input.txt content:
5 9 2 9 3
8 2 8 2 1
0
In Enclipse, it goes to infinite-loop. I'm using MinGW 5.1.6 + Eclipse CDT.
I tried many things but I couldn't find the problem.
Since you are on windows try:
} while (line != "0\r");
The last line is stored as "0\r\n". The \n is used as the line delimiter by getline so the actual line read will be "0\r"
or
you can convert the dos format file to UNIX format using command
dos2unix input.txt
Now your original program should work. The command will change the \r\n at the end of the line to \n
Also you should always do error checking after you try to open a file, something like:
inputFile.open("input.txt");
if(! inputFile.is_open()) {
cerr<< "Error opening file";
exit(1);
}
It will create an infinite loop if no line contains exactly 0. For example 0\n is not the same thing as 0. My guess is that that is your problem.
EDIT: To elaborate, getline should be discarding the newline. Perhaps the newline encoding of your file wrong (i.e. windows vs. unix).
Your main problem is working directory.
Because you are specifying a file using a relative path it searches for the file from the current working directory. The working directory can be specified by your dev environment. (Note: The working directory is not necessarily the same directory where the executable lives (this is a common assumption among beginners but only holds in very special circumstances)).
Though you have a special end of input marker "0" you should also check that the getline() is not failing (as it could error out for other reasons (including beady formatted input). As such it is usually best to check the condition of the file as you read it.
int main()
{
string line;
ifstream inputFile;
inputFile.open("input.txt");
while((getline(inputfile, line)) && (line != "0"))
{
// loop only entered if getline() worked and line !="0"
// In the original an infinite loop is entered when bad input results in EOF being hit.
cout << line << endl;
}
if (inputfile)
{
cout << line << endl; // If you really really really want to print the "0"
// Personally I think doing anything with the termination
// sequence is a mistake but added here to satisfy comments.
}
return 0;
}