Opening a file not working [closed] - c++

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
#include <iostream>
#include <iomanip>
#include <cmath>
#include <fstream>
#include <string>
#include <cstdlib>
using namespace std;
int main() {
ifstream input_file("DataStuff.txt", ios::in);
//trying to open the notepad file named DataStuff.txt
if(!input_file){
cerr << "Error" << endl; exit(1);
}
else{
cout << "good 2 go" << endl;
}
}

Try this:
#include <cstring>
#include <fstream>
#include <iostream>
int main() {
std::ifstream input_file("DataStuff.txt", ios::in);
if (input_file) {
std::cout << "ok\n";
} else {
std::cerr << "error: " << strerror(errno) << "\n";
return 1;
}
return 0;
}
The output should give you some idea what is going on. Most likely the file doesn't exist or the permissions are incorrect.
Further explanation: If the file couldn't be opened then the constructor for std::ifstream sets errno to a value indicating what the error was. You can access strings describing the error using the strerror() function (defined in <cstring>).
Good luck!

"Opening a file" is used in the sense that there is a connection established between the file: "DataStuff.txt" and your program, by the input stream, ifstream object named input_file which allows you to read from the file.
One possible cause for the file to not open is if it doesn't exist (including wrong name).
Another cause is if the file permissions do not allow access, for example if you are not owner of the file and its set to private.
To get more information about the actual cause you should probably acquaint yourself with stream rdstates and integrate them in your code to check the state of the stream after you try to open it.

Related

My program will not open text file. Ofstream CPP

I'm currently new to C++ and I've been watching a tutorial series https://www.youtube.com/watch?v=_bYFu9mBnr4, but I'm having a big issue. My C++ code will not open a file no matter what I do, I've looked online and tried renaming it, the full path, everything I can think of. Here's my code,
#include <iostream>
#include <fstream>
#include <cstring>
#include <cerrno>
#include <filesystem>
int main()
{
std::ofstream file;
file.open("hello.txt");
if (!file.is_open())
{
std::cerr << "Error: " << strerror(errno) << '\n';
std::cout << std::filesystem::current_path() << std::endl;
}
file << "hello!";
file.close();
return 0;
}
Sorry about this question, it may have been a dumb issue. Turns out IT WAS my antivirus. Avast kept blocking it, it was just looking out for me. I decided to change my antivirus afterwards and it now works fine!

why rename function in c++ isn't working? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I'm trying to do some testings for a project that I'm working on. I tried to rename a file and it doesn't work at all, what am I doing wrong?
I already tried to check the close() and remove() functions.
#include <fstream>
#include<iostream>
#include <string>
using namespace std;
int main() {
fstream guy;
guy.open("testing.txt", fstream::out);
guy << "i love halav" << endl;
fstream guy1;
guy1.open("test1.txt", fstream::out);
guy1 << "i love halav" << endl;
guy.close();
guy1.close();
remove("testing.txt");
int result = rename("testing1.txt", "testing.txt");
if (result == 0)
cout << "File successfully renamed" << endl;
else
cout << "Error renaming file" << endl;
guy1.close();
return 0;
}
edit: i edit the code so it will be more cear, again its not working .
the rearult im expecting is that the content of newFile.txt wil be "this is oldFile"
#include <fstream>
#include<iostream>
#include <string>
#include <cstdio>
using namespace std;
int main() {
fstream guy;
guy.open("oldFile.txt", fstream::out );
guy << "this is oldFile" << endl;
fstream guy1;
guy1.open("newFile.txt", fstream::out );
guy1 << "this is newFile" << endl;
guy.close();
guy1.close();
std::rename("oldFile.txt", "newFile.txt");
remove("oldFile.txt");
return 0;
}
With std::rename your first argument is supposed to be the old filename and the second argument is supposed to be the new filename. You've swapped the arguments, so try:
std::rename("testing.txt", "testing1.txt");
... but don't std::remove("testing.txt"); before you rename the file since it'll remove it.
now thats the way to do it, thanks everyone!
#include <fstream>
#include<iostream>
#include <string>
#include <cstdio>
using namespace std;
int main() {
fstream guy;
guy.open("oldFile.txt", fstream::out );
guy << "this is oldFile" << endl;
fstream guy1;
guy1.open("newFile.txt", fstream::out );
guy1 << "this is newFile" << endl;
guy.close();
guy1.close();
remove("newFile.txt");
std::rename("oldFile.txt", "newFile.txt");
return 0;
}

ifstream.open() not opening file for reading and writing

i am trying to open file for read/write purpose. Below code is not working ?
can anyone explain me where i m doing wrong?
#include <iostream>
#include <fstream>
int main()
{
using namespace std;
ifstream file;
file.open("program.txt");
if (!file)
{
cout << "failure";
}
return 0;
}
the output of above program is "failure".
but why?
isn't it supposed to open file sucessfully?
If you are using linux / macos. try this code, it will show you the reason of failure.
#include <iostream>
#include <fstream>
#include <stdio.h>
int main()
{
using namespace std;
ifstream file;
file.open("program.txt");
if (!file)
{
perror("open failure");
}
return 0;
}
I guess the reason is "No such file or directory".
Maybe you can try to switch your "current directory" to find the file.
I got the same issue and did some research and not find the cause.
later I tried it using absolute path for the file and find it works.
file.open("program.txt");
------> should be
file.open("/absolute path/program.txt");

Why is this not producing a file in the current directory?

I have some trouble with producing files in C++. I consulted this answer here but when I try using it, it doesn't produce a file. What I wrote:
//~/Documents/Test_CPP/ex2/main_2.cpp
#include <fstream>
int main()
{
std::ofstream file("Hello.txt");
// Hello.txt has been created here
}
I compile it with the command g++ main_2.cpp and run it with ./a.out. I don't really know what could go wrong here, except theorizing that the file might be produced not in the current directory but somewhere else. So I tried changing Hello.txt to ~/Documents/Test_CPP/ex2/Hello.txt, which doesn't change anything. What exactly am I doing wrong here?
I have encountered this problem on macOS with Xcode if you use some IDEs you should point to build-dir.
My suggestion: use std::filesystem::current_path(). It will give full path to you elf\exe dir.
#include <string>
#include <iostream>
#include <filesystem>
#include <fstream>
int main() {
std::string file_name{"Hello.txt"};
auto path{std::filesystem::current_path()};
path = path / file_name;
if (std::filesystem::exists(path)) {
std::filesystem::remove(path);
}
std::ofstream out_stream(path, std::ios::out);
if (!out_stream.is_open()) {
std::cerr << "Error open file" << std::endl;
return -1;
}
out_stream << "test" << std::endl;
out_stream.close();
return 0;
}
This can sometimes happen if you do not properly terminate the connection to the file
EG.
file.close();
This must be done before the program terminates.

Check whether file name already exists in a folder or not?

In C++ I need to check whether a entered file name exists in that folder or not. I'm writing code for Linux, using the g++ compiler.
please help guys :)
I saw this code somewhere on net for my problem but I strongly feel it wont serve my purpose:
ofstream fout(filename);
if(fout)
{
cout<<"File name already exists";
return 1;
}
You can do this by testing with an ifstream, but there is a subtle difference between using that and the C level stat() interface.
#include <cerrno>
#include <cstring>
#include <iostream>
#include <fstream>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
using namespace std;
int main (int argc, const char *argv[]) {
if (argc < 2) {
cerr << "Filepath required.\n";
return 1;
}
ifstream fs(argv[1]);
if (fs.is_open()) {
fs.close();
cout << "ifstream says file exists.\n";
} else cout << "ifstream says file does not exist.\n";
struct stat info;
if ((stat(argv[1], &info)) == -1) {
if (errno == ENOENT) cout << "stat() says file does not exist.\n";
else cout << "stat() says " << strerror(errno) << endl;
} else cout << "stat() says file exists.\n";
return 0;
}
If you run this on a file that exists and you have read permission on, you'll get the same answer both ways.
If you run this on a file that does not exist, you get the same answer both ways.
If you run this on a file that exists but you do not have read permissions on, you'll get two different answers. fstream will say the file does not exist, but stat() will say it does. Note that if you run ls in the same directory, it will show the file, even though you cannot read it; it does exist.
So if the last case is not significant -- i.e., a file you can't read might as well not exist -- then use the ifstream test. However, if it is important, then use the stat() test. See man 2 stat (the 2 is important) for more, and remember, to use it you need:
#include <cerrno>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
cerrno is required to check errno if stat() fails, which can happen. For example, if read permission on a directory in the path is denied, then stat() will fail and errno will be equal to EACCES; if you try it with the above program you'll get stat() says Permission denied. This does not mean the file exists. It means you can't check whether it exists or not.
Beware, if you have not used errno before: You must check immediately on a failed call, before you make any others which may set it differently. It is, however, thread safe.
If you want to be cross-platform and C++'y I recommend the Boost Filesystem library.
For your purposes I think something similar to this Boost sample code
#include <iostream>
#include <boost/filesystem.hpp>
using namespace boost::filesystem;
int main(int argc, char* argv[])
{
path p (argv[1]); // p reads clearer than argv[1] in the following code
if (exists(p)) // does p actually exist?
{
if (is_regular_file(p)) // is p a regular file?
cout << p << " size is " << file_size(p) << '\n';
else if (is_directory(p)) // is p a directory?
cout << p << "is a directory\n";
else
cout << p << "exists, but is neither a regular file nor a directory\n";
}
else
cout << p << "does not exist\n";
return 0;
}
would do the job.
Maybe what you want is fstat:
http://codewiki.wikidot.com/c:system-calls:fstat