I've tried to write to file in C++ on a mac in different ways and I can't.
I've used:
int bestScore = 3;
QFile data("bestScore.txt");
data.open(QIODevice::WriteOnly);
QTextStream out(&data);
out << bestScore;
data.close();
int bestScore = 3;
FILE *out_file = fopen("bestScore.txt", "w");
if (out_file == NULL)
{
qDebug() << "File not open";
}
fprintf(out_file, "%d", bestScore);
Can anyone help?
First thing you need to include fstream.
Second you declare the name of the file as an variable.
You need to open it.
#include <iostream>
#include <fstream>
using namespace std;
int main () {
ofstream myfile;
myfile.open ("example.txt");
myfile << "Writing this to a file.\n";
myfile.close();
return 0;
}
If this dosen't work try to give the exact location of the file example
myfile.open ("/Library/Application/randomfilename/example.txt");
Related
i'm trying to write a script in c++ which read a CSV file so i can treat it later .i ve used fstram but the file always fail to open**
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main(){
string filename = "hello.txt"; // could come from command line.
ifstream fin(filename.c_str());
if (!fin.is_open())
{
cout << "Could not open file: " << filename << endl;
return 1;
}
cout<<"khalil"<<endl;
string scores[32];
string names[32];
int iter = 0;
while (iter <= 5)
{
fin >> names[iter] >> scores[iter];
cout << iter <<"\n";
cout<<names[iter]<< "\n";
cout<<scores[iter]<<"\n";
iter++;
}
fin.close();
}
Try using a fully qualified path name, e.g.:
string filename = "C:\\Documents\\hello.txt";It appears your program isn't opening the file because it can't find it.
You can use QFile class to do this operation.
#include <QFile>
#include <QStringList>
#include <QDebug>
int main()
{
QFile file("C\\hello.txt");
if (!file.open(QIODevice::ReadOnly)) {
qDebug()<<file.errorString();
return 0;
}
QStringList firstList, secondList;
while (!file.atEnd()) {
QByteArray line = file.readLine();
firstList.append(line.split(',')[0]);
secondList.append(line.split(',')[1]);
}
qDebug()<<firstList;
qDebug()<<secondList;
}
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;
}
Premise: I'm using CLion.
As i said in title, when i try to open a file (txt) nothing will be displayed.
i can't explain it, i don't think i made an error, it's pretty easy this code:
#include <iostream>
#include <cstdlib>
using namespace std;
int main() {
FILE *leggi;
leggi = fopen("lorem.txt", "r");
char datiLetti[1000];
while(fgets(datiLetti, 1000, leggi)!=NULL){
cout << datiLetti << endl;
}
fclose(leggi);
system("PAUSE");
return EXIT_SUCCESS;
}
file "lorem.txt" is in the same directory of the project.
Thank you in advance.
EDIT1: file is lorem not lorem_ipsum, my mistake when i typed here.
You want this:
...
FILE *leggi;
leggi = fopen("lorem.txt", "r");
if (leggi == NULL)
{
cout << "Can't open file" << endl;
return 1;
}
...
---FIXED---
Installed cygwig1.dll and cygstdc++-6.dll and put cygwig in glob variables, then my file worked in the same directory of main and exe.
However, thank you guys for your time!
fopen is a C solution for open a file if you want to open a file in c++ use fstream like flowing code.
fopen is deprecated in c++11.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
string line;
fstream myfile;
myfile.open("example.txt");
cerr << "Error: " << strerror(errno);
if (myfile.is_open())
{
while (getline(myfile, line))
{
cout << line << '\n';
}
myfile.close();
}
else cout << "Unable to open file";
return 0;
}
I'm looking to create a file, then open it and rewrite to it.
I've found I can create a file by simply doing this:
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
ofstream outfile ("test.txt");
outfile << "my text here!" << endl;
outfile.close();
return 0;
}
while this works to create the test file, I cannot open the file and then edit it. this (below) does not work even after the file is created.
outfile.open("test.txt", ios::out);
if (outfile.is_open())
{
outfile << "write this to the file";
}
else
cout << "File could not be opened";
outfile.close;
If by "does not work" you mean that the text is overwritten instead of appended, you need to specify std::ios::app as one of the flags to the call to open to have it append more data instead of overwriting everything.
outfile.open("test.txt", ios::out | ios::app);
The following example works fine for me:
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
ofstream outfile ("test.txt");
outfile << "my text here!" << endl;
outfile.close();
outfile.open("test.txt", ios::out | ios::app );
if (outfile.is_open())
outfile << "write this to the file" << endl;
else
cout << "File could not be opened";
outfile.close();
return 0;
}
Produces the following text file:
my text here!
write this to the file
You can also do that with FOPEN. Some compilers will notice you that the function its OBSOLETE or DEPRECATED but for me its working good.
/* fopen example */
#include <stdio.h>
int main ()
{
FILE * pFile;
pFile = fopen ("myfile.txt","w");
if (pFile!=NULL)
{
fputs ("fopen example",pFile);
fclose (pFile);
}
return 0;
}
More info here: http://www.cplusplus.com/reference/cstdio/fopen/
I just need to write a string into a file created using ofstream, but I am getting an error.
This is the code:
#include <iostream>
#include <fstream>
using namespace std;
int main ()
{
QString aux = "Hello";
ofstream myfile ("test.txt");
if (myfile.is_open())
{
myfile << aux;
myfile.close();
}
else
{
cout << "CANT OPEN FILE";
}
return 0;
}
The error is: no match for 'operator<<' in 'myfile << aux'
P.S: I am using QT4
Thanks for your help!
You should convert to a string by doing :
myfile << aux.toStdString();
This is because the << operator does not know any conversion from qt string.