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/
Related
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");
ifstream fin;
fin.open("C:\\Users\\Zach\\Desktop\\input.txt");
if (!fin)
{
cout << "e";
}
e is printing whether I use the full pathway or just input.txt from a resource file
If the file exists, make sure that you have got the path specified correctly. Since you're running on Windows, you can verify the full path to your executable with the following code.
#include <iostream>
#include <fstream>
#include <string>
#include <windows.h>
#define BUFSIZE 4096
std::string getExePath()
{
char result[BUFSIZE];
return std::string(result, GetModuleFileName(NULL, result, BUFSIZE));
}
int main()
{
std::ifstream infile("input.txt");
if (infile.is_open())
{
std::cout << "Success!" << std::endl;
infile.close();
}
else
{
std::cout << "Failed to open input.txt!" << std::endl;
std::cout << "Executable path is ->" << getExePath() << "<-" << std::endl;
}
return 0;
}
This will allow you to verify that your path to the input file is correct, assuming that it's collocated with your executable.
You need to direct output into the ifstream object by using fin << "string"; and not directing to standard out via cout.
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 am reading data from a comma delimited csv file. I would like to verify that the file has data before reading and return an error if the file doesn't have any data.
const char* sample_data_file = "sample_data1.csv" ;
std::ifstream file(sample_data_file);
Thanks!
A simple call to stat will tell you if the file is empty. That should be enough to solve your problem.
check the size of the file when you open it?
// reading a text file
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main ()
{
ifstream myfile ("C:/temp/sample1.csv");
// this gives you the number of bytes in the file.
if (myfile.is_open())
{
long begin, end;
begin = myfile.tellg();
myfile.seekg (0, ios::end);
end = myfile.tellg();
if(end-begin == 0)
{
cout << "file is empty \n";
}
else
{
cout << "size: " << (end-begin) << " bytes." << endl;
}
myfile.close();
}
else cout << "Unable to open file \n";
return 0;
}
#include <iostream>
#include <fstream>
using namespace std;
int main ()
{
ofstream testfile;
testfile.open ("test.txt");
testfile << "success!\n";
testfile.close();
return 0;
}
1)called "g++ testfile.cpp"
2)created "test.txt"
3)called "chmod u+x a.out"
4)???
5)file remains blank.
I feel like an idiot for failing at something as trivial as this is supposed to be.
When performing file I/O, you almost always need to test for errors:
#include <iostream>
#include <fstream>
using namespace std;
int main ()
{
ofstream testfile;
testfile.open ("test.txt");
if ( ! testfile.is_open() ) {
cerr << "file open failed\n";
return 1;
}
if ( ! testfile << "success!\n" ) {
cerr << "write failed\b";
return 1;
}
testfile.close(); // failure unlikely!
return 0;
}
In theory they're equivalent, but just to make sure, do try << endl instead of "\n" to flush the stream.
ofstream testfile;
testfile.open ("test.txt");
testfile << "success!" << endl;
testfile.close();