#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();
Related
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.
i m trying to read from a file and stop when i hit end of line. the thing is, it doesnt seem to work.¯_(ツ)_/¯ any ideas why?
#include <iostream>
#include <fstream>
using namespace std;
int main(){
char a;
ifstream myfile;
myfile.open("text.txt");
while (!myfile.eof())
{
myfile>> a;
if (a=='\n')
cout << "end of line";
}
myfile.close();
}
text file i read:
Try while (myfile.get(a)) instead?
while (myfile.get(a))
{
if (a=='\n')
cout << "end of line";
}
Why make things harder than needed. If you want to parse lines, then use std::getline().
#include <iostream>
#include <fstream>
int main(int argc, char *argv[]) {
std::ifstream myfile("text.txt");
std::string line;
while (std::getline(myfile, line)) {
std::cout << "end of line" << std::endl;
}
}
using a for loop
std::ifstream ifs( "file" );
for( char chr = 0; ifs.peek() != '\n'; ifs.get( chr ) ){
std::cout << chr;
}
ifs.close();
I just rewrite your code:
#include <iostream>
#include <fstream>
using namespace std;
int main(){
char a;
ifstream myfile;
myfile.open("/Users/sijan/CLionProjects/test2/text.txt",ifstream::in);
while (myfile.get(a))
{
cout<< a;
if (a=='\n')
cout << "end of line\n";
}
if (myfile.eof())
cout << "end of file";
myfile.close();
}
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 need to write two programs write.cpp & read.cpp to run simultaneously. One of them write(overwrite) to a file and the other one reads from it.
Basically, there is always only one line in the file.
write.cpp performs the operation successfully but read.cpp doesn't show anything. Using tail -f also shows incorrect result.
write.cpp:
#include <stdio.h>
#include <ctime>
#include <unistd.h>
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main () {
ofstream myfile;
int i = 70;
char c;
while(i <85)
{
myfile.open ("example.txt");
c = i++;
myfile << c << endl;
myfile.close();
sleep(1);
}
return 0;
}
read.cpp:
#include <iostream>
#include <fstream>
#include <string>
#include <unistd.h>
using namespace std;
int main () {
string line;
ifstream myfile ("example.txt");
if (myfile.is_open())
{
while ( myfile.good() )
{
sleep(1);
getline (myfile,line);
cout << line << endl;
}
myfile.close();
}
else cout << "Unable to open file";
return 0;
}
May I know which part of both programs causes the problem and how may I solve it?
You're doing the right thing in the writer, but once you've read to end of file, the input stream becomes unusable until the fail condition is set. The best solution is probably to do exactly what you're doing in the writer: open and close the file each time in the read loop.
Be aware that there will be a moment when the file is empty; when you open the file for writing in the writer, it will be truncated, and if the reader happens to try to read at precisely this moment, it will find an empty file. (It's no big problem; just be aware of it, maybe skipping the sleep if you find an empty line.)
To add some detail to my answer to your previous question, here is how you could use Boost's interprocess communication to achieve this if you insist on using a file for ipc.
A writer may look like this:
#include <boost/interprocess/sync/file_lock.hpp>
#include <boost/interprocess/sync/scoped_lock.hpp>
#include <fstream>
#include <iostream>
int main()
{
using namespace boost::interprocess;
std::string line, shared_filename = "shared";
{
std::ofstream create_shared_file(shared_filename.c_str());
}
for (;;)
{
std::cout << "Enter some text: ";
std::cin >> line;
try
{
file_lock lock(shared_filename.c_str());
scoped_lock<file_lock> lock_the_file(lock);
std::ofstream shared_file(shared_filename.c_str(), std::ofstream::trunc);
shared_file << line << std::endl;
shared_file.flush();
}
catch (interprocess_exception const& e)
{
std::cerr << e.what() << std::endl;
}
}
}
The corresponding reader:
#include <boost/interprocess/sync/file_lock.hpp>
#include <boost/interprocess/sync/sharable_lock.hpp>
#include <fstream>
#include <iostream>
#include <unistd.h>
int main()
{
using namespace boost::interprocess;
std::string line, shared_filename = "shared";
for (;;)
{
try
{
file_lock lock(shared_filename.c_str());
std::cout << "Waiting for file lock..." << std::endl;
sharable_lock<file_lock> lock_the_file(lock);
std::cout << "Acquired file lock..." << std::endl;
std::ifstream shared_file(shared_filename.c_str());
shared_file >> line;
if (line.empty())
{
std::cout << "Empty file" << line << std::endl;
}
else
{
std::cout << "Read: " << line << std::endl;
}
}
catch (interprocess_exception const& e)
{
std::cerr << "Could not lock " << shared_filename << ": " << e.what() << std::endl;
}
std::cout << "Sleeping..." << std::endl;
sleep(2);
}
}