This question already has an answer here:
How to append to a file with fstream fstream::app flag seems not to work
(1 answer)
Closed 8 years ago.
I try to append file in C++. At start file doesn't exists. After operations there is only one line in file instead of five (5 calls of this method). It looks like file is creating, next every write operation file is cleaned out and new string is added.
void storeUIDL(char *uidl) {
fstream uidlFile(uidlFilename, fstream::app | fstream::ate);
if (uidlFile.is_open()) {
uidlFile << uidl;
uidlFile.close();
} else {
cout << "Cannot open file";
}
}
I tried with fstream::in ,fstream::out. How to append string correctly in this file?
Thank you in advance.
edit:
Here is wider point of view:
for (int i = 0; i < items; i++) {
MailInfo info = mails[i];
cout << "Downloading UIDL for email " << info.index << endl;
char *uidl = new char[100];
memset(uidl, 0, 100);
uidl = servicePOP3.UIDL(info.index);
if (uidl != NULL) {
if (existsUIDL(uidl) == false) {
cout << "Downloading mail with index " << info.index << endl;
char *content = servicePOP3.RETR(info);
/// save mail to file
string filename = string("mail_" + string(uidl) + ".eml");
saveBufferToFile(content, filename.c_str());
storeUIDL(uidl);
sleep(1);
} else {
cout << "Mail already exists." << endl;
}
} else {
cout << "UIDL for email " << info.index << " does not exists";
}
memset(uidl, 0, 100);
sleep(1);
}
This works.. std::fstream::in | std::fstream::out | std::fstream::app .
#include <fstream>
#include <iostream>
using namespace std;
int main(void)
{
char filename[ ] = "Text1.txt";
fstream uidlFile(filename, std::fstream::in | std::fstream::out | std::fstream::app);
if (uidlFile.is_open())
{
uidlFile << filename<<"\n---\n";
uidlFile.close();
}
else
{
cout << "Cannot open file";
}
return 0;
}
It looks like this question has been answered over yonder.
Give this a shot:
fstream uidFile(uidFilename, fstream::out | fstream:: app | fstream::ate);
Edit:
I wrote this code and compiled it in Visual Studio 2012 on Windows 7 x64. It works perfectly for me. It looks like the other answer worked for you, but please let me know if this does as well.
#include <iostream>
#include <fstream>
using namespace std;
void save(char * string)
{
fstream myFile("test.txt", fstream::out | fstream::app);
if(myFile.is_open())
{
myFile.write(string, 100);
myFile << "\n";
}
else
{
cout << "Error writing to file";
}
}
int main()
{
char string[100] = {};
for(int i = 0; i < 5; i++)
{
for(int j = 0; j < 100; j++)
{
string[j] = i + 48; //48 is the ASCII value for zero
}
save(string);
}
cin >> string[0]; //Pause
return 0;
}
Related
And thisI am trying to get the things written in a .txt file called CodeHere.txt and here is my main.cpp:
#include <iostream>
#include <fstream>
using namespace std;
int main(int argc, const char * argv[]) {
string line;
string lines[100];
ifstream myfile ("CodeHere.txt");
int i = 0;
if (myfile.is_open())
{
while ( getline (myfile,line) )
{
lines[0] = line;
i++;
}
myfile.close();
}
else cout << "Unable to open file";
cout << lines[0];
myfile.close();
return 0;
}
And the output is: Writing this to a file.Program ended with exit code: 0
But in my CodeHere.txt it has: hello
I tried saving it, but the result didn't change. I'm not sure whats going on. Can anyone help?
Are you sure that your .txt file is in the same repertory? To me, it just looks like you entered the path wrong. Try with the absolute path (full one). Another option is that you haven't saved the text file yet, you're just editing it, and so it is in fact empty, that would be why your cout doesn't print anything.
This should work, using a vector<string> to store the lines read from file
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
int main(int argc, const char * argv[]) {
string line;
vector<string> lines;
ifstream myfile ("CodeHere.txt");
int i = 0;
if (myfile.is_open())
{
while ( getline(myfile, line) )
{
lines.push_back(line);
i++;
}
myfile.close();
}
else {
cout << "Unable to open file";
return -1;
}
cout << lines[0] << '\n';
return 0;
}
Try this:
vector<string> lines;
if (file.is_open()) {
// read all lines from the file
std::string line;
while (getline(file, line)) {
lines.emplace_back(line);
}
file.close();
}
else {
cout << "Unable to open file";
return -1;
}
cout << "file has " << lines.size() << " lines." << endl;
for (auto l : lines) {
cout << l << endl;
}
EDIT :
Turns out that the problem is that in iosfwd, it throws the exception at line 506 :
Exception thrown: write access violation.
_Left was 0xCCCCCCCC.
To answer :How to Fix: Exception thrown: write access violation. _Left was 0xCCCCCCCC
I am making a program where it launches another program in its same directory that updates a text file using ShellExecute.
The program begins by taking a string using getline and then uses ShellExecute to launch another program that uses fstream to update a file.
Here is the relevant part of the program:
cout << "Please enter Program Name:" << endl;
getline(cin.ignore(), a);
system("cls");
os.open("tempstring.txt");
os << a;
os.close();
LPCSTR filename = "NewProgScript.exe";
LPCSTR Location = NULL;
ShellExecute(NULL, "open", filename, NULL, Location, SW_SHOWNORMAL);
/*>> >> >> >> >> rest is irrelevant << << << << << <<*/
bool end = false;
do
{
system("cls");
is.open("tempdone.txt");
is >> x;
is.close();
if (x == 1) { end = true; }
if (x == 2) { os.open("tempdone.txt"); os << 0; os.close(); Errors Err; Err.Error(41); }
cout << "Please wait while Files Update." << endl;
Sleep(1000);
} while (end == false);
"NewProgScript.exe" is launched here.
NewProgScript.exe code:
#include "pch.h"
#include <fstream>
#include <string>
#include <Windows.h>
#include <iostream>
using namespace std;
int main()
{
ofstream os;
ifstream is;
string a, nouse;
string Progs[20];
is.open("tempstring.txt");
getline(is, nouse);
is.close();
cout << "UPDATING DATABASE.. DO NOT EXIT!" << endl;
string name, ending, end;
ending = ".txt";
name = "Prog";
for (int count = 1; count < 20 + 1; count++)
{
end = name + to_string(count) + ending;
is.open(end);
getline(is, Progs[count]);
is.close();
}
for (int count = 1; count < 20 + 1; count++)
{
end = name + to_string(count) + ending;
if (Progs[count] == "NULL")
{
os.open("end");
os << nouse;
os.close();
os.open("tempdone.txt");
os << 1;
os.close();
Sleep(500);
exit(EXIT_SUCCESS);
}
}
os.open("tempdone.txt");
os << 2;
os.close();
}
The problem is that when this is launcher early on using ShellExecute, it does not update the file "tempdone.txt"
It does however work when I manually click open it externaly.
How can i fix this?
P.S: sorry for the Very long post! Also I am sorry of i make dumb or naive mistakes, i am not very good yet :/
I encountered a funny issue with this code but I am wondering why this happened:
#include <stdio.h>
#include <unistd.h>
#include <iostream>
#include <wiringPi.h>
#define BUTTON_PORT 25
#define FILE_PATH "/path/to/output.txt"
int main(void) {
int buttonState = 0;
int pastButtonState = 0;
int buttonCounter = 0;
if (wiringPiSetupGpio() == -1) return 1;
pinMode(BUTTON_PORT, INPUT);
while(buttonCounter < 100){
if (buttonState == 1 && pastButtonState == 0) buttonCounter++;
usleep(100);
ofstream outputfile(FILE_PATH);
outputfile << buttonCounter << endl;
outputfile.flush();
outputfile.close();
pastButtonState = buttonState;
}
I expected output.txt to show current # of buttonCounter,
but file is always empty, and 1 of 10 times the file shows # of buttonCounter.
(with continuously exec less /path/to/output.txt)
I know certain repeat of ofstream outputfile in while loop is not a good solution, but I have no idea why output.txt is usually empty.
I might think it's ugly to use ofstream outputfile in while loop since ofstream outputfile takes some time since it's a bit high-level function.
While putting outputfile -related function into
if (buttonState == 1 && pastButtonState == 0) {...}
works fine. Any ideas?
I would a add check to make sure the file was opened successfully. Also, the results of executing less on the file is not a reliable method to test the contents of the file while you are running the program. usleep(100) does not give you enough time to check the contents of the file before it is opened again.
I suggest the following change to your code.
while(buttonCounter < 100){
if (buttonState == 1 && pastButtonState == 0) buttonCounter++;
writeToFile(buttonCounter, FILE_PATH);
showContentsOfFile(FILE_PATH);
`
pastButtonState = buttonState;
}
where writeToFile is:
void writeToFile(int buttonState, std::string const& file)
{
std::ofstream outputfile(file);
if ( outputfile )
{
outputfile << buttonCounter << std::endl;
}
else
{
std::cerr << "Unable to open " << file << " for writing to.\n";
}
}
and showContentsOfFile is:
void showContentsOfFile(std::string const& file)
{
std::ifstream inputfile(file);
if ( outputfile )
{
int buttonCounter;
if ( inputfile >> buttonCounter )
{
std::cout << "Button counter: " << buttonCounter << std::endl;
}
else
{
std::cerr << "Unable to read buttonCounter from file " << file << std::endl;
}
}
else
{
std::cerr << "Unable to open " << file << " for reading from.\n";
}
}
I have a vector of strings of 2 folder names vector <myClass> vec_fileNames; which I filled by reading from a fileNames.txt which contains 2 lines:
First
Second
ifstream inFile("c:/file names.txt");
if(!inFile)
{
cout << "File Not Found!\n";
inFile.close();
}
else
{
string line;
myClass class;
while (getline(inFile, line))
{
class.setFileName(line);
vec_fileNames.push_back(class);
}
So, at this point my vec_fileName[0].getFileName = First and vec_fileName[1].getFileName = second
Now I wanted to open files inside the folders who's names are in the vector in a loop so I did this:
for(int i = 0; i < vec_fileNames.size(); i++)
{
string fileName = vec_fileNames[i].getFileName();
ifstream inFile("C:/Program Folder\\" + fileName + "goalFile.txt");
if(!inFile)
{
cout << "File Not Found!\n";
inFile.close();
}
else
{
while (getline(inFile, line))
{
//do something
}
}
So far everything is good except for the file not being opened. Is this even something that can be done in c++ or is there an error in the way I'm opening the file?
I created the same folder structure as you have:
C:\
Program Folder
First
goalFile.txt
Second
goalFile.txt
And ran the following simple code. Node that I don't store the filenames in a class, but directly into a vector.
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
using namespace std; // I'm no fan of this, but you obviously used it.
void loadFileNames(vector<string>& vec_fileNames)
{
ifstream inFile("c:\\file names.txt");
if(!inFile.is_open())
{
cout << "File Not Found!\n";
return;
// inFile.close(); -- no need to close, it is not open!
}
else
{
string line;
while (getline(inFile, line))
{
cout << line << endl;
vec_fileNames.push_back(line);
}
}
}
void openFiles(vector<string>& vec_fileNames)
{
for(int i = 0; i < vec_fileNames.size(); i++)
{
string fileName = vec_fileNames[i];
string path("C:\\Program Folder\\" + fileName + "\\goalFile.txt");
ifstream inFile(path.c_str());
if(!inFile.is_open())
{
cout << "File" << vec_fileNames[i] << "Not Found!" << endl;
}
else
{
cout << "opened file in folder " << vec_fileNames[i] << endl << endl;
string line;
while (getline(inFile, line))
{
cout << line << endl;
}
cout << endl;
}
}
}
int main(int argc, char* argv[])
{
vector<string> fileNames;
loadFileNames(fileNames);
openFiles(fileNames);
return 0;
}
That works, and produces the output:
First
Second
opened file in folder First
First goal file 1
First goal file 2
opened file in folder Second
Second goalfile 1
Second goalfile 2
The lines First goal file 1, etc. are the contents of the two files.
I feel like I've tried everything, I can get the first file to append to the second but cannot get the second file into a third. What am I doing wrong?
To be clear I need to take one file, append it to a second file, then put the contents of that second file into a third. I was able to simulate this outcome by putting both files into strings and then putting those strings into a third file, but that's not 'correct' in this problem.
I'm not particular to any way or any technique, I've tried a few and nothing works. This is the latest attempt, still doesn't work for the last step.
Here's my code:
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main()
{
string a,b,c;
cout << "Enter 3 file names: ";
cin >> a >> b >> c;
fstream inf;
ifstream two;
fstream outf;
string content = "";
string line = "";
int i;
string ch;
inf.open(a, ios::in | ios:: out | ios::app);
two.open(b);
outf.open(c, ios::in);
//check for errors
if (!inf)
{
cerr << "Error opening file" << endl;
exit(1);
}
if (!two)
{
cerr << "Error opening file" << endl;
exit(1);
}
if (!outf)
{
cerr << "Error opening file" << endl;
exit(1);
}
for(i=0; two.eof() != true; i++)
content += two.get();
i--;
content.erase(content.end()-1);
two.close();
inf << content;
inf.clear();
inf.swap(outf);
outf.close();
inf.close();
return 0;
Here's an idea:
#include <fstream>
using namespace std;
void appendf( const char* d, const char* s )
{
ofstream os( d, ios::app );
if ( ! os )
throw "could not open destination";
ifstream is( s );
if ( ! is )
throw "could not open source";
os << is.rdbuf();
}
int main()
{
try
{
appendf( "out.txt", "1.txt" );
return 0;
}
catch ( const char* x )
{
cout << x;
return -1;
}
}