In test.txt file i have one word "aa". I want to replace it with "aa1". However, the program below does not change the file. What's wrong?
#include <string>
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
fstream iofile("test.txt",ios_base::in|ios_base::app);
if (!iofile)
cerr << "Unable to open file!";
string word;
iofile >> word;
word.push_back('1');
iofile.seekg(0);
iofile << word;
}
You realize that ios_base::app is causing you to append to the end of the file no matter where you try to seek for write, right? Maybe you meant to specific ios_base::out instead?
Also, for writes, it's seekp() not seekg().
Related
Im new to c++ and i was trying to open a ".txt" file using ifstream. the file im using is called "ola.txt" which literally just contains two lines of text without punctuation just plain and simple text. The code that i wrote is this
#include <iostream>
#include <vector>
#include <fstream>
#include <iomanip>
#include <string>
using namespace std;
int main()
{
int x;
string line;
vector<int> vect;
ifstream inFile("C:\\Users\\ruial\\Desktop\\ola.txt");
inFile.open("C:\\Users\\ruial\\Desktop\\ola.txt");
if (inFile.is_open()) {
while (getline(inFile, line))
{
cout << line << '\n';
}
inFile.close();
}
else {
cout << "Unable to open file";
exit(1); // terminate with error
}
return 0;
}
The path to the file that i wrote is correct such that the file opens, but when the program runs it doesn´t cout the lines that i wrote on the txt file to the cmd, i dont know if this is somewhat important but im coding in visual studio 2019.
I can't seem to find the answer to this problem anywhere in the internet and to be honest i think im doing it right, any help would be much appreciated,thanks in advance.
You are trying to open the inFile twice. First time during inFile construction, ifstream inFile("C:\\Users\\ruial\\Desktop\\ola.txt"), second time you try to open it again with inFile.open("C:\\Users\\ruial\\Desktop\\ola.txt"), when it's already open, which is erroneous, and flags the stream as no longer good.
3 possible fixes:
Remove inFile.open("C:\\Users\\ruial\\Desktop\\ola.txt")
Use default constructor, without specifying the file name
inFile.close() before you open it again (obviously, not the nicest fix).
I'm trying to write some text to a file and then read it using only 1 fstream object.
My question is very similar to this question except for the order of the read/write. He is trying to read first and then write, while I'm trying to write first and then read. His code was able to read but did not write, while my code is able to write but not read.
I've tried the solution from his question but it only works for read-write not write-read.
Here is my code:
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
fstream fileObj("file.txt", ios::out|ios::in|ios::app);
// write
fileObj << "some text" << endl;
// read
string line;
while (getline(fileObj, line))
cout << line << endl;
}
The code writes some text to file.txt successfully but it doesn't output any text from the file. However, if I don't write text to the file (remove fileObj << "some text" << endl;), the code will output all text of the file. How to write first and then read the file?
This is because your file stream object has already reached the end of the file after the write operation. When you use getline(fileObj, line) to read a line, you are at the end of the file and so you don't read anything.
Before beginning to read the file, you can use fileObj.seekg(0, ios::beg) to move the file stream object to the beginning of the file and your read operation will work fine.
int main()
{
fstream fileObj("file.txt", ios::out | ios::in | ios::app);
// write
fileObj << "some text" << endl;
// Move stream object to beginning of the file
fileObj.seekg(0, ios::beg);
// read
string line;
while (getline(fileObj, line))
cout << line << endl;
}
Although this answer doesn't qualify for your requirement of "reading and writing a file simultaneously", keep in mind that the file will most likely be locked while being written to.
Here the simple example to write and read the file.
Hope it will help you.
#include<fstream>
using namespace std;
int main ()
{
ofstream fout ("text.txt"); //write
ifstream fin ("text.txt"); // read
fout<<"some text";
string line;
while (fin>> line) {
cout<<line;
}
return 0;
}
I'm having some problems reading a string into an array. my file contains the following strings running horizontally down the page.
File:
dog
cat
rabbit
mouse
Code:
#include <string>
int i = 0;
using namespace std;
int main()
{
FILE * input1;
fopen_s(&input1, "C:\\Desktop\\test.dat", "r");
string test_string;
while (!feof(input1)) {
fscanf_s(input1, "%s", test_string);
i++;
}
return 0;
}
Any advice would be appreciated, Thanks!
You should use ifstream and std::getline
Now, I'm going to walk you through reading lines from the file using ifstream
Include fstream to use ifstream.
#include <fstream>
Opening a file:
To open a file, create an object of ifstream, and call it's method open and pass the filename as parameter. ifstream opens a file to read from it. (To write in a file, you can use ofstream)
ifstream fin;
fin.open("C:\\Desktop\\test.dat");
Or you can simply pass the filename to the constructor to create an object of ifstream and open a file.
ifstream fin("C:\\Desktop\\test.dat");
Reading from the file:
You can use stream extraction operator (>>) to read from the file, just like you use cin
int a;
fin >> a;
To read a line from a file using the above created fin (using a char array)
char arr[100];
fin.getline(arr, 100);
Better yet, you should use std::string instead or char arrays, using std::string, you can read a line using std::getline
string testString;
getline(fin, testString);
Now, let's change your code to use ifstream and getline
#include <string>
#include <fstream>
#include <iostream>
using namespace std;
int main()
{
int i = 0;
ifstream input1;
input1.open("C:\\Desktop\\test.dat");
string test_string;
while (getline(input1, test_string)) {
i++;
}
return 0;
}
I want to display all the text that is in the fille to the output,
I use by using the code below, the code I got up and results posts are just a little out
#include <fstream>
#include <iostream>
using namespace std;
int main()
{
char str[10];
//Creates an instance of ofstream, and opens example.txt
ofstream a_file ( "example.txt" );
// Outputs to example.txt through a_file
a_file<<"This text will now be inside of example.txt";
// Close the file stream explicitly
a_file.close();
//Opens for reading the file
ifstream b_file ( "example.txt" );
//Reads one string from the file
b_file>> str;
//Should output 'this'
cout<< str <<"\n";
cin.get(); // wait for a keypress
// b_file is closed implicitly here
}
The above code simply displays the words "This" does not come out all into output.yang I want is all text in the file appear in the console ..
The overloaded operator>> for char* will only read up to the first whitespace char (it's also extremely risky, if it tries to read a word longer then the buf length you'll end up with undefined behavior).
The following should do what you want in the most simple manner, as long as your compiler supports the rvalue stream overloads (if not you'll have to create a local ostream variable and then use the stream operator):
#include <fstream>
#include <iostream>
int main()
{
std::ofstream("example.txt") << "This text will now be inside of example.txt";
std::cout << std::ifstream("example.txt").rdbuf() << '\n';
}
try something like this
#include <fstream>
#include <iostream>
using namespace std;
int main(){
string line;
ofstream a_file ( "example.txt" );
ifstream myfile ("filename.txt");
if (myfile.is_open()) {
while ( getline (myfile,line) ) {
a_file << line << '\n';
}
myfile.close();
a_file.close();
} else
cout << "Unable to open file";
}
Hope that helps
This is not the best way to read from a file. You probably need to use getline and read line by line. Note that you are using a buffer of fixed size, and you might cause an overflow. Do not do that.
This is an example that is similar to what you wish to achieve, not the best way to do things.
#include <fstream>
#include <iostream>
using namespace std;
int main() {
string str;
ofstream a_file("example.txt");
a_file << "This text will now be inside of example.txt";
a_file.close();
ifstream b_file("example.txt");
getline(b_file, str);
b_file.close();
cout << str << endl;
return 0;
}
This is a duplicate question of:
reading a line from ifstream into a string variable
As you know from text input/output with C++, cin only reads up to a newline or a space. If you want to read a whole line, use std::getline(b_file, str)
When I debug this I can see it opens datafile1 , it reads the firstline and
in the logfile I get roma-3-4.log
It change to c:/temp/roma-3-4.log but when I want to open it , it fails. I have check that the _Mystate = 2 .
What is the meaning of that
Thanks
in the transfersubs.cfg there is this
roma-3-4.log
** In the directory c:/temp/ I have the following file
roma-3-4.log
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
using namespace std;
int main()
{
string input;
string logfile;
string errorfile;
short logfilesize1;
fstream dataFile1("c:/temp/transfersubs.cfg", ios::in);
if (dataFile1)
{
getline(dataFile1, input, '$');
logfile=input;
logfilesize1=input.size();
errorfile=input;
errorfile[logfilesize1-4]='e';
errorfile[logfilesize1-3]='r';
errorfile[logfilesize1-2]='r';
logfile="C:/Temp/"+logfile;
fstream dataFile2( logfile, ios::in);
if (dataFile2)
{
dataFile2.close();
}
else
{
cout << "ERROR: Cannot open logfile.\n";
}
dataFile1.close();
}
else
{
cout << "ERROR: Cannot open file.\n";
}
system("Pause");
return 0;
}
I believe your getline doesn't bother looking the newline but only for a $. You didn't post the file you are reading from, but check to ensure it has a $ at the end of the file name otherwise it will fetch the entire file.
It appears that unless you put a \n or endl after writing to the file using ofstream, ifstream won't be able to read anything from the file. In fact, adding a space after whatever you've written into file won't help either.
So always add a newline right after whatever it is that you've written to file using ofstream.