Strange fstream problem - c++

I have really strange problem. In Visual C++ express, I have very simple code, just:
#include <fstream>
using namespace std;
int main()
{
fstream file;
file.open("test.txt");
file<<"Hello";
file.close();
}
This same code works OK in my one project, but when I create now project and use this same lines of code, no file test.txt is created. Please, what is wrong?ยจ
EDIT: I expect to see test.txt in VS2008/project_name/debug - just like the first functional project does.

Canonical code to write to a file:
#include <fstream>
#include <iostream>
using namespace std;
int main() {
ofstream file;
file.open("test.txt");
if ( ! file.is_open() ) {
cerr << "open error\n";
}
if ( ! ( file << "Hello" ) ) {
cerr << "write error\n";
}
file.close();
}
Whenever you perform file I/O you must test every single operation, with the possible exception of closing a file, which it is not usually possible to recover from.
As for the file being created somewhere else - simply give it a weird name like mxyzptlk.txt and then search for it using Windows explorer.

Perhaps the executable is run in a different directory than it was before, making test.txt appear somewhere else. Try using an absolute path, such as "C:\\Users\\NoName\\Desktop\\test.txt" (The double backslashes are needed as escape characters in C strings).

fstream::open() takes two arguments: filename and mode. Since you are not providing the second, you may wish to check what the default argument in fstream is or provide ios_base::out yourself.
Furthermore, you may wish to check whether the file is open. It is possible that you do not have write permissions in the current working directory (where 'test.txt' will be written since you don't provide an absolute path). fstream provides the is_open() method as one way of checking this.
Lastly, think about indenting your code. While you only have a few lines there, code can soon become difficult to read without proper indentation. Sample code:
#include <fstream>
using namespace std;
int main()
{
fstream file;
file.open("test.txt", ios_base::out);
if (not file.is_open())
{
// Your error-handling code here
}
file << "Hello";
file.close();
}

You can use Process Monitor and filter on file access and your process to determine whether the open/write is succeeding and where on disk it's happening.

Theres two ways to fix this. Either do:
file.open("test.txt", ios::out)
#include <fstream>
using namespace std;
int main()
{
fstream file;
file.open("test.txt", ios::out);
file<<"Hello";
file.close();
}
Or you can create an ofstream instead of fstream.
#include <fstream>
using namespace std;
int main()
{
ofstream file;
file.open("test.txt");
file<<"Hello";
file.close();
}

Related

Trying creating and writing into a txt file in C++

Basically, I'm following a simple tutorial about files handling in C++.
I've been trying to create and write into a txt file at the same time, but any of the methods I've tried won't actually create a txt file in my executable location.
I should also say that, I print myfile.is_open() just to know if the file truly created and opened, but I get 0 everytime with every method.
What am I doing wrong ?
I mainly tried to create and write to a txt file like this:
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
fstream myfile;
myfile.open("example.txt", ios::out);
cout << myfile.is_open() << endl;
myfile << "Writing this to a file.\n";
myfile.close();
}
First, I bet you're using an IDE like Visual Studio. Most IDEs set your working directory somewhere other than your project directory. I don't use Visual Studio, but many of them put them in ../.
So your file is being produced, but not where you think you should find it.
If you compile and run this program without an IDE, you'll get your file where you expect it.
You may also be able to tell your IDE that the working directory should be your project directory.
Now, to keep you from making a few bad habits, I'm going to tell you two more things.
It's considered a mistake to do using namespace std. Instead, I do using statements only on those things I am going to use frequently. In your short code, I wouldn't have done any.
Next, if you're going to write out a file, it's better to use std::ofstream. It's otherwise the same code. But it's a bit clearer that you're only using the file for output.
So my version of your code:
#include <iostream>
#include <fstream>
int main()
{
std::ofstream myfile;
myfile.open("example.txt");
std::cout << myfile.is_open() << std::endl;
myfile << "Writing this to a file.\n";
myfile.close();
}
Yeah, those std:: everywhere can be annoying, so you could do this:
#include <iostream>
#include <fstream>
using std::ofstream;
using std::cout;
using std::endl;
int main()
{
ofstream myfile;
myfile.open("example.txt");
cout << myfile.is_open() << endl;
myfile << "Writing this to a file.\n";
myfile.close();
}
I actually have an include of CommonUsing.h that I put a few things I do almost everywhere.
#pragma once
#include <chrono>
#include <iostream>
#include <date/date.h>
//======================================================================
// The most common using statements I do in most of my code.
//======================================================================
using std::cout;
using std::cerr;
using std::endl;
using std::string;
using namespace std::chrono_literals;
using date::operator<<;

ifstream does not open a file in the next iteration

I have two similar methods that open a file identically, but process them and return values a bit differently, yet while the first method does that successfully, the second method, which is called after the first one, fails.
I have tried changing the path to this file, its extension, but I think I miss some important knowledge about ifstream.
vector<User> Database::createUserDatabase()
{
vector<User> users;
ifstream inputFile;
inputFile.open(pathToFile, ios::in);
//Some file processing
inputFile.close();
return users;
}
And that works perfectly, while
vector<User> Database::createBookDatabase()
{
vector<Book> books;
ifstream inputFile;
inputFile.open(pathToFile, ios::in);
//Some file processing
inputFile.close();
return books;
}
fails to end whenever I check if the file has been opened or not using
inputFile.is_open()
These functions are defined in class files Database.cpp, User.cpp, Book.cpp, which are correctly linked to the main.cpp with the following content:
#include <iostream>
#include <cstdlib>
#include <string>
#include <cstring>
#include <sstream>
#include <vector>
#include <fstream>
#include "../lib/Book.h"
#include "../lib/User.h"
#include "../lib/Database.h"
using namespace std;
int main()
{
Database userDatabase("../database/users.txt", "users");
Database bookDatabase("../database/lmsdb.txt", "books");
vector<User> users = userDatabase.createUserDatabase();
vector<Book> books = bookDatabase.createBookDatabase();
return 0;
}
Here are my Project directories
Using gdb debugger, I have confirmed that the file is not being opened at all. I assume that I did not close the files properly, but I have a little knowledge of C++ yet (been learning it for only a week or so).
Looking forward to see what you can suggest reading/researching, yet I really would like to see a straightforward solution to this problem.
I assume that I did not close the files properly, [..]
Yes, but that probably isn't the cause of the issue. The C++ way is to not close them explicitly. Due to RAII, the ifstream will close itself once it goes out of scope (i.e. when the enclosing function terminates).
There are many reasons why a file could fail to open, including:
It doesn't exist.
Trying to open a read-only file in write mode.
The file is in use by another process. (Maybe you have it opened in an editor?)
Insufficient privileges (e.g. due to the file being protected).

C++ Stream class failed to open the file

I write small test application in C++ to read the file data, So when I used the C++ -Stream class to read from files, it fails to open the file stream for the file name which gets passed as argument of the Stream class object.
Also I keep my file(Test.txt) in the directory where my program executable is kept and run.
#include<fstream>
#include<string>
#include<iostream>
using namespace std;
int main(int argc, char *argv[])
{
ifstream testFile("Test.txt");
string line;
if (testFile.is_open())
{
while (getline(testFile, line))
{
line += line;
}
}
}
please also find the additional debug capture which has been captured from visual studio debugger.
If you run a program from the editor/IDE it is not always true (and generally it isn't) that the root directory for relative paths is the project directory or the one where the .exe is placed. If you run the executable from the command line placed in the directory it should work, but if you run it when the command line isn't in the directory you'll see the same error.
If you want the root directory to be the project one there is certainly an option in the editor/IDE, just surf the web or look into settings (probably run configurations)
The answer is: The file could not be opened. It is mispelled, or not existing.
But most likely it is in a different directory.
Please use a full path for the file, then you can open it. Like
ifstream testFile("c:\\temp\\Test.txt");
Then, please do not use is_open.
Simply use
if (testFile)
The ! operator for ifstream is overwritten, so this will work.
thanks all and I manage to get it working with the platform independent method. Please see the code below.
#include<fstream>
#include<string>
#include<stdlib.h>
#include<iostream>
#include <errno.h>
#include <filesystem>
using namespace std;
namespace fs = std::filesystem;
int main(int argc, char *argv[])
{
fs::path Path = fs::current_path() / argv[1];
ifstream testFile(Path.c_str());
string line;
string str;
if (testFile.is_open())
{
for (std::string line; std::getline(testFile, line);)
{
str += line;
}
}
std::cout << str << endl;
}

Cannot create a txt file using fstream::open

I have two files and in one I have created simple class :
#include <iostream>
#include <fstream>
#include <string>
#include <time.h>
#include <stdlib.h>
#include <conio.h>
#include <unistd.h>
class myclass{
protected:
int ima,imb,imc,tm;
fstream file;
public:
void creafile(string filename){
string dir;
dir = "txtfile/";
file.open((dir + filename).c_str(), ios::in | ios::out);
if(file.fail()){
// file.open(filename, ios::in | ios::out);
//if(file.fail())
cout<<"Error when creating the file"<<endl;
exit(1);
}
file.close();
}}
and my main file is called data.cpp and contain only this code:
using namespace std;
#include "mylib.h"
int main() {
myclass dat,hi;
dat.creafile("creatorfile.txt");
return 0;
}
My problem is that I always get an error when calling creafile Error when creating the file. To make a simpler test case, I also tried the following code:
file.open("myfile.txt");
if(!file){
cout<<"Error when creating the file"<<endl;
exit(1);
}
file.close();
However, it still gives the error Error when creating the file. I've tried using all flags ios::app ios::in ios::out etc but nothing changes. I have 500gb free space, and running Windows 7.
According to the reference, ios::in | ios::out std::ios_base::openmode configuration will an generate error if the file does not exist, so you won't create a new one with that.
I don't know why you're using the member std::fstream, createfile could just be a static function that does not change any object. You're even closing it afterwards! It would create a file using a local std::ofstream, open mode of which is std::ios_base::out, which will create the file:
std::ofstream ofs(dir + filename); // .c_str() not needed since C++11
Point 1: You cannot open to read if the file doesn't exist. Fortunately you probably don't want to. Simultaneously reading and writing the same file is problematic and almost always a bad idea. Until you know you have to read and write at the same time,
open the file for reading
read in the file
close the file.
edit the file in memory
open the file for writing
write out the file
close the file
If you have a really big file you can't store in memory,
open the file for reading
open a temporary file for writing
read in part of the file
edit the part you read
write the part you read to temporary
if more file, goto 3 (but don't use goto), else continue
close file
close temporary file
delete file
rename temporary file to file
Point 2: You have created the txtfile folder, but have you created it in the right place? Your development environment (include of conio.h suggests Visual Studio or antique) may not be running your program from where you think it is running.
Add this to your code in main:
char buf[4097]; // really big buffer
getcwd(buf, (int)sizeof(buf)); // get working directory
std::cout << buf << std::endl; // print the working directory
If the folder printed out is not where you made the txtfile folder, you can't open the file. If you want to automatically make the folder, read here: How to make a folder/directory
Point 3: exit(1); is a really big hammer. It is a nasty hammer. Read more here. Don't use it without a really, really good reason. In this case return is more than enough to get you out of the function, and if you add a return value to the function, main can test the return value to see if it should continue or return. Or you can throw an exception.

Writing To a file using fstream will erase the file

I have a problem, I have a saved text file, I want to use fstream header file in C++ to write something to that file, but using ofstream will erase the whole file as soon as I run the compiled application, why and how to avoid it?
#include <fstream>
#include <iostream>
using namespace std;
int main()
{
ofstream write("1.txt");
return 0;
}
You need to tell ofstream to append to the file.
std::ofstream write("1.txt",std::ios::app);
There are several other flags that control similar characteristics of the stream, read a book or reference for more information.