This is my code
#include <iostream>
#include <fstream>
#include <string>
int main()
{
std::fstream file;
file.open("text.txt", std::fstream::in | std::fstream::out |
std::fstream::app);
if(!file.is_open())
{
std::cout << "Could not open file(test.txt)" << std::endl;
} else {
file << "These are words \nThese words are meant to show up in the new file \n" <<
"This is a new Line \nWhen the new fstream is created, all of these lines should be read and it should all copy over";
std::string text;
file >> text;
std::cout << text << std::endl;
file.close();
std::fstream newFile;
newFile.open("text2.txt", std::fstream::in | std::fstream::out |
std::fstream::app);
if(newFile.is_open())
{
newFile << text;
}
}
}
I'm trying to copy the contents of text.txt to text2.txt but for some reason the text string always ends up empty. I've checked the files and text gets populated but text2 is empty. What's going wrong here?
When you append a string to an fstream, the input / output position is set to the end of the file. This means that when you next read from the file, all you will see is an empty string.
You can check what the current input position is by using:
file.tellg()
And set the input / output position to the start by using:
file.seekg(0)
The full reference for std::fstream is here.
You're trying to read from the end of the file. The position is set to the end of the last thing you wrote to the file, so, if you want to read what you wrote, you have to reset it:
file.seekg(0);
This will set the position for the input back to the start of the file. Note however that reading from the file the way you do now will simply get you 1 word (up to the first whitespace). If you want to read it all, perhaps you should look at something like: Read whole ASCII file into C++ std::string.
Related
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 opened a file both read and write mode
using the following statement
file.open(fileName, ios::in | ios::out | ios::trunc);
my main purpose for opening the file in both mode is, read and write the file at the same time.
But In my code scenario,
when I am reading the file after writing it, the ouput showing blank that means,
it is not saving my writing contents because I am not closing it.
And I want to close the file after finishing both write and read the operation
I found a solution in Stack Overflow,
to use flush() function to save the file without closing
file.flush();
but, the problem is it's not working for my case
So, how can I save c++ fstream file without closing?
Here's my full code for better understanding
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main(int argc, char const *argv[])
{
string fileName = "text.txt";
fstream file;
file.open(fileName, ios::in | ios::out | ios::trunc);
if (file.is_open())
{
file << "I am a Programmer" << endl;
file << "I love to play" << endl;
file << "I love to work game and software development" << endl;
file << "My id is: " << 1510176113 << endl;
file.flush(); // not working
}
else
{
cout << "can not open the file: " << fileName << endl;
}
if (file.is_open())
{
string line;
while(file)
{
getline(file, line);
cout << line << endl;
}
}
else
{
cout << "can not read file: " << fileName << endl;
}
file.close();
return 0;
}
Actually, if you want to save any file immediately without closing the file, then you can simply use
file.flush();
But if you are want to read the file without closing just after writing it, you can simply use
file.seekg(0);
actually seekg() function resets the file pointer at the beginning, for this, it is not mandatory to save the file. so, this has nothing to with flush() function
but you can do both if you want to
Before reading from that file you need to make sure to place the pointer to that file to the beginning of the file. After writing to the file it'll point to the end. Therefore you won't be able to read anything.
You need to use file.seekg(0); somewhere after the file.flush() but before starting to read to place the file pointer to the very beginning.
Update
This should work without the flush. However this will depend on the implementation of the std library. Although I'd consider this as bug if it doesn't work without calling flush() imho it does not hurt to call it explicitly.
I have a C++ (Made in Netbeans 8 in Mac OS X 10.9) that in short writes to a file then ends the program. Here is the Meat of my program.
#include <iostream>
#include <fstream>
#include <sstream>
ofstream outfile("NETBEANS_PMCL.txt");
if(outfile.fail())
{
cout << "Cant open that file." << endl;
return 0;
}
outfile << "name" << endl;
outfile.close();
return 0;
But each time I run the program it rewrites on top of the name that was printed the last time I ran the program. How do I make it so that if there is content on the first line then skip two lines and print and if there is content there skip two lines and print and so on.
The problem is that ofstream is to write to a file, and what you want is to read to see if there is content, skeep 2 lines, and write new content.
std::fstream file("NETBEANS_PMCL.txt", std::fstream::in | std::fstream::out | std::fstream::app);
After that you may try to read 2 line and write content. Consider the function member getline to read the content.
getline (char* s, streamsize n, char delim );
Can Some one help me the problem with this code? I am getting bunch of garbage value !
fstream fs("hello.txt");
if(fs.is_open())
{
string s = "hello";
string line;
fs << s;
while(getline(fs,line))
{
cout << line;
}
cin.get();
}
fs.close();
Thank you very much but when I try to do this I am getting same garbage. I am trying to rewrite the first hello with world and trying to print that line
fstream fs("hello.txt");
if(fs.is_open())
{
string s = "hello";
string line;
fs << s << endl;
fs.seekg(0);
fs << "world" << endl;
fs.seekg(0);
while(getline(fs,line))
{
cout<<line;
}
cin.get();
}
fs.close();
The cursor of fs is at the end of file after you fs << s (this is required to append data to the file properly).
Try to call fs.seekg(0); to move the cursor back to the beginning.
Also, you may need to supply the fstream::trunc or fstream::app flag when constructing fs.
fstream fs("hello.txt", fstream::in | fstream::out | fstream::trunc);
If hello.txt is empty prior to running the program then it seems to work for me. If the file contains more than 6 or 7 characters then your hello world code will overwrite the first 6/7 chars with "world" followed by the line terminator (which might be 1 or 2 chars depending on the platform). The reminder of the file won't be overwritten and will be subsequently printed by your getline loop.
How to append text to a text file in C++? And create a new text file if it does not already exist and append text to it if it does exist.
You need to specify the append open mode like
#include <fstream>
int main() {
std::ofstream outfile;
outfile.open("test.txt", std::ios_base::app); // append instead of overwrite
outfile << "Data";
return 0;
}
I use this code. It makes sure that file gets created if it doesn't exist and also adds bit of error checks.
static void appendLineToFile(string filepath, string line)
{
std::ofstream file;
//can't enable exception now because of gcc bug that raises ios_base::failure with useless message
//file.exceptions(file.exceptions() | std::ios::failbit);
file.open(filepath, std::ios::out | std::ios::app);
if (file.fail())
throw std::ios_base::failure(std::strerror(errno));
//make sure write fails with exception if something is wrong
file.exceptions(file.exceptions() | std::ios::failbit | std::ifstream::badbit);
file << line << std::endl;
}
#include <fstream>
#include <iostream>
FILE * pFileTXT;
int counter
int main()
{
pFileTXT = fopen ("aTextFile.txt","a");// use "a" for append, "w" to overwrite, previous content will be deleted
for(counter=0;counter<9;counter++)
fprintf (pFileTXT, "%c", characterarray[counter] );// character array to file
fprintf(pFileTXT,"\n");// newline
for(counter=0;counter<9;counter++)
fprintf (pFileTXT, "%d", digitarray[counter] ); // numerical to file
fprintf(pFileTXT,"A Sentence"); // String to file
fprintf (pFileXML,"%.2x",character); // Printing hex value, 0x31 if character= 1
fclose (pFileTXT); // must close after opening
return 0;
}
You could use an fstream and open it with the std::ios::app flag. Have a look at the code below and it should clear your head.
...
fstream f("filename.ext", f.out | f.app);
f << "any";
f << "text";
f << "written";
f << "wll";
f << "be append";
...
You can find more information about the open modes here and about fstreams here.
You could also do it like this
#include <fstream>
int main(){
std::ofstream ost {outputfile, std::ios_base::app};
ost.open(outputfile);
ost << "something you want to add to your outputfile";
ost.close();
return 0;
}