My question is how can I get my console to properly display the contents of fileB based on the below information.
Below is the code I have created for basic file input/output operations. I am trying to copy the content from fileA over to fileB. After this is done I am trying to display the contents of fileB to cout. The code runs and updates the contents of fileB to whatever was stored in fileA. However, the console does not display the new content of fileB. It just shows a blank box.
#include <iostream> // Read from files
#include <fstream> // Read/Write to files
#include <string>
#include <iomanip>
void perror();
int main()
{
using std::cout;
using std::ios;
using std::ifstream;
ifstream ifile; // ifile = input file
ifile.open("fileA.txt", ios::in);
using std::ofstream;
ofstream ofile("fileB.txt", ios::out); // ios::app adds new content to the end of a file instead of overwriting existing data.; // ofile = output file
using std::fstream;
fstream file; // file open fore read/write operations.
if (!ifile.is_open()) //Checks to see if file stream did not opwn successfully.
{
cout << "File not found."; //File not found. Print out a error message.
}
else
{
ofile << ifile.rdbuf(); //This is where the magic happens. Writes content of ifile to ofile.
}
using std::string;
string word; //Creating a string to display contents of files.
// Open a file for read/write operations
file.open("fileB.txt");
// Viewing content of file in console. This is mainly for testing purposes.
while (file >> word)
{
cout << word << " ";
}
ifile.close();
ofile.close();
file.close();
getchar();
return 0; //Nothing can be after return 0 in int main. Anything afterwards will not be run.
}
fileA.txt
1
2
3
4
5
fileB.txt (file is initially a blank text document).
fileB.txt (after code runs)
1
2
3
4
5
ofile will have an internal buffer and if it isn't flushed and you only write a small amount of data (possibly as much as 64kb) then no data will be written to your output file until you call ofile.close() or at the end of main().
Simply move ofile.close() to before file.open("fileB.txt").
This happens because you haven't closed the oFile object before you open the FileB.
ofile.close();
file.open("fileB.txt");
By doing this you will have access to the updated file.
I hope that this helps you.
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;
}
This is my first post and I'm fairly new to C++. I am currently looking for a way to save multiple variables to a file (XML or TXT) so it looks like this:
charactername:George
level:5
I would also like to be able to read these and put them into a variable.
Ex:
std::string characterName = "George";
(but it would read George from the line in the file charactername:George)
I have a total of 68 variables (48 strings, 11 ints, and 9 bools) I want in 1 file.
Does anyone know a way to do this or a tutorial they could point me towards? I have found was to save 1 string to a file, but not multiple variables of different types.
I think you should learn how to use a datafile matrix,
But before that here is some basic file management code for you to try use, you'll be able to read in data and recover it based on a structured layout, when recovering your bool data use an implicit conversion to change from a string.
Here are some basic file operations, this will create a txt file that has data on new lines:
// basic file operations
// writing on a text file
#include <iostream>
#include <fstream>
using namespace std;
int main () {
ofstream myfile ("example.txt");
if (myfile.is_open())
{
myfile << "This is a line.\n";
myfile << "This is another line.\n"; // this will for data onto a new line to be read later.
myfile.close();
}
else cout << "Unable to open file";
return 0;
}
How to recover data, this will put the data into a string array which you can then use to recall data from in your code:
// how to retrieve the data:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main () {
string line, data_array[67];
ifstream myfile ("example.txt");
if (myfile.is_open())
{
while ( getline (myfile,line) )
{
data_array[i] = line; i++;
}
myfile.close();
}
else cout << "Unable to open file";
return 0;
}
How to edit data, you'll need to have a function to read in all your variables and rewrite the whole text file as unless each line is exactly the same byte you can not jump directly to it.
To look more into detail you should learn how to use a datafile matrix, here are some nice videos to get you started.:
C++ Tutorial (Reading Rows and Columns from datafile Matrix
Matrix in C++ | Part #1 | simple matrix definition using arrays
#include <iostream>
#include <fstream>
#include <stdlib.h>
#include <process.h>
using namespace std;
int main(){
system("cls");
char mline[75];
int lc=0;
ofstream fout("out.txt",ios::out);
ifstream fin("data.txt",ios::in);
if(!fin){
cerr<<"Failed to open file !";
exit(1);
}
while(1){
fin.getline(mline,75,'.');
if(fin.eof()){break;}
lc++;
fout<<lc<<". "<<mline<<"\n";
}
fin.close();
fout.close();
cout<<"Output "<<lc<<" records"<<endl;
return 0;
}
The above code is supposed to read from the file "data.txt" the following text
"The default behaviour of ifstream type stream (upon opening files ) allows users
to read contents from the file. if the file mode is ios::in only then reading is
performed on a text file and if the file mode also includes ios::binary along with
ios::in then, reading is performed in binary mode. No transformation of characters
takes place in binary mode whereas specific transformations take place in text mode."
and create a file out.txt , in which the same text is stored using line numbers ( A line can have 75 characters or ends at '.' - whichever occurs earlier ).
Whenever I run the program, it just gets stuck at the console - which doesnt respond upon pressing any keys whatsoever.
Can someone tell me what's going on in here ?
If any one of the attempted reads in the file is longer than 74 characters, getline will set the failbit for fin, and you will never reach the end of the file. Change your code to the following:
for (; fin; ++lc) {
fin.getline(mline,75,'.');
if (!fin.eof() && !fin.bad())
fin.clear();
fout<<lc<<". "<<mline<<"\n";
}
This will break your loop if you reach the end of the file or if something catastrophic happens to the stream. You'll also need to think about handling the extra read that is performed if the file ends with a period.
Consider switching to std::string.
#include <iostream>
#include <fstream>
#include <string>
int main()
{
int lc = 0;
std::ofstream fout("out.txt");
std::ifstream fin("data.txt");
for (std::string line; getline(fin, line, '.'); )
fout << ++lc << ". " << line << "\n";
std::cout << "Output " << lc << " records\n";
}
Simple program to open up a file and read it's contents. Then a test at the end to see if I did in fact get the information. Every time I run it it tells me that it cannot open the file. I will post the contents of SaleSlips below. Why isn't it opening the file? It is also attempting to delete the file every run as well.
#include <iostream>
#include <fstream>
#include <cstdlib>
using namespace std;
struct SaleSlip{
char name[20];
int prodID;
double value;
};
void main(){
fstream slips;
SaleSlip sales[17];
slips.open("SaleSlips.txt", ios::in);
if(slips.eof()){
cout << "Cannot open file - SaleSlips.txt"<< endl;
system("pause");
exit(2);
}
int i = 0;
while(!slips.eof()){
slips.getline(sales[i].name, ' ');
slips >> sales[i].prodID;
slips.ignore(5, ' ');
slips >> sales[i].value;
slips.ignore(80, ' ');
i++;
}
cout << sales[1].value;
slips.close();
system("pause");
}
Eric 1 200000.00
Sookie 2 200.00
Sookie 4 200.50
You're opening the stream in output mode by using ios::out. Use ios::in to read from it.
You've got a lot of other issues, too. IE:
-The if(!slips.eof()) after the file open will always cause an exit unless the file is empty.
-In your while loop, you are (probably accidentally) attempting to write the prodID and value into the slips file using <<. Use >> to read from a stream and << to write to it.
You have two problems:
You're opening the file for output (writing)
slips.open("SaleSlips.txt", ios::out);
Useios::in instead for input (reading)
slips.open("SaleSlips.txt", ios::in);
Next, you're immediately testing for !eof(), which is the wrong logic.
if(!slips.eof())
You don't want to be at eof() when opening the file for input. eof() is end of file. When first opening the file for input you want to be at the beginning of the file; being at eof() is a bad thing. Your code should error out if eof() is true, not if it's false:
if(slips.eof()) {
// It's an error if we're starting at eof()
}
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.