Ifstream cannot open file with amdinistrator rights - c++

I used this code to try to open and read the file (not empty), but ifstream did not work - it could not open the file: I addded the check on file opening and it showed, that ifstream even did not (could not) open the file.
I gave administrator rights to the program, but ifstream still could not read the file.
I also tried to find a path, where ifstream would read this file, but I did not success, and at last I tried to open file using the absolute path - but result is the same.
The file is situated in the root folder of the program, but I placed it everywhere and nothing changed.
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main() {
string s;
ifstream file("fix.txt");
if (file)
cout << "SUCCESSFULL OPENING" << endl;
while (getline(file, s)) {
cout << s << endl;
s += "+";
cout << s << endl;
}
file.close();
return 0;
}

You may have access to a more detailed error code by activating exceptions on the stream via
file.exceptions(std::ios_base::failbit);
Then, you get more details by writing
try {
file.open("fix.txt");
}
catch(std::ios_base::failure& f) {
// f.what() contains a message, f.code() returns a std::error_code
}

Related

Can't open file properly in C++

I'm trying to read each line from a .geom file and save that in a string.
The user shall input the correct (absolute) filepath and then, until now, should get the content of the .geom file printed out on the console.
The problem is that under every circumstance it seems impossible to open the file via my c++ program.
Everytime I check if the file is opened via is_open() it responds with false.
The program, my IDE and the .geom file are all on the same drive and i am currently using windows. The IDE im using is Codeblocks and the executable is build in it.
This is my complete code until now:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
//a function to check if the given file has the .geom extension
bool isGeom(string file){
if(file.substr(file.find_last_of(".") + 1) == "geom") {
return true;
} else {
return false;
}
}
//main func
int main()
{
string filepath, geomInput, line;
cout << "----- GeomView2obj -----" << endl;
cout << "Please enter a valid file path to a .geom file to convert it to an .obj file: \n" << endl;
//get file path by user
getline(cin, filepath);
//declare stream and open file if possible
ifstream geomFile (filepath.c_str());
if(!geomFile.is_open()){
cout << "\nERR: The given file path is invalid or the file does not exist!" << endl;
return 1;
}
if(!isGeom(filepath)){
cout << "\nERR: The given file is not a .geom file!" << endl;
return 1;
}
//read chars from geom file
while(getline(geomFile, line)){
geomInput.append(line + "\n");
}
//print string --- DELETE
cout << geomInput;
geomFile.close();
return 0;
}
I also tried to first declare my ifstream and then opening the file.
I also turned the user input off and entered an absolute path where every folder was seperated with two backslashes \\ instead of one.
I also copied the file to the folder the compiled program lies in and giving the program a relative path to the file as an input, but that also did not help.
Any form of help is much appreciated!

ifstream says it opened a file but the file doesnt open

I am using visual studio 2017
I am new to c++ and here I tried to open a txt file, and confirming that it was opened.
#include <iostream>
#include <fstream>
#include <String>
using namespace std;
int main()
{
ifstream infile;
string text;
infile.open("C:\\Users\\gab_a\\source\\repos\\one\\testing.txt");
if (!infile.is_open()) {
cerr << "Specified file could not be found ";
exit(1);
}
else {
cout << "Opened file ";
infile >> text;
cout << text;
}
return 0;
}
it says that it opened it, and it even read the text that was inside the file, but the actual file isn't opening, I even put the file in the same directory as the project. There are also no errors, so why isn't my file opening?
What you're doing is reading the data from the file into a stream. This is not the same as executing a program to open the file. To do that is generally OS specific, but if you're on Windows you can use ShellExecute or CreateProcess. I do suggest you brush up on your C++ a bit - no offense intended

Open a file with C++ and output the text that is in the file

I am trying to open a file with C++ and output the text that is in the file. I cannot seem to figure out what I am doing wrong. Here is what I have so far.
#include <iostream>
#include <string>
#include <fstream>
#include <cstdlib>
using namespace std;
int main()
{
char fileName[50];
ifstream infile;
cout << "Enter the name of the file you would like to open: ";
cin.getline(fileName, 50);
infile.open(fileName);
if(!infile.is_open())
{
exit(EXIT_FAILURE);
}
char line[75];
infile >> line;
while (infile.good())
{
cout << line << " ";
infile >> line;
}
system("pause");
return 0;
}
After I input the file name and press enter the CMD prompt just closes. I know that the file exist, but I cannot figure out why it is exiting. Obviously it is because of the exit command, but it should be open. What am I doing wrong?
You don't need to read/write the file line by line; C++ already supports to copy the file in one step. You also should use string instead of char[] for your strings; on one hand it means that you don't need to restrict the maximal length of your strings to some arbitrary length (what if your file's pathname has more than 50 characters, or the file has lines with more than 75 characters?
Note also that your file copying code is erroneous: It will remove all whitespace from the file, as infile >> line does not read a line (use readline for that), but a word, discarding whitespace.
Also, your code should give an error message if it couldn't open the file, instead of just silently returning (you do provide an error return, which is very good, but unless you call it from something that actually gives you feedback on the error return, you'll never learn about it.
Finally, the system("pause") should probably be done in an RAII class, so it is guaranteed to be exited on return (however, exit will not call destructors, so unless you want to use atexit, you should use return in `main`` instead). A better idea would, however, be to not put this into the code, but instead run it in a terminal that doesn't immediately close after the program finishes.
Here's a program that implements those suggestions:
#include <iostream>
#include <fstream>
#include <cstdlib>
int main()
{
// make sure that system("pause") is called on all exit paths
struct cleanup
{
~cleanup() { std::system("pause"); }
} do_cleanup;
// get the file name
std::string filename;
std::cout << "Enter the name of the file you would like to open: ";
std::getline(std::cin,filename);
if (!std::cin)
{
std::cerr << "Failed to read the file name.\n";
return EXIT_FAILURE;
}
// open the file
std::ifstream infile(filename.c_str());
if (!infile)
{
std::cerr << "Could not open file: " << filename << "\n";
return EXIT_FAILURE;
}
// print the file
std::cout << infile.rdbuf();
// close the file
infile.close();
if (!infile)
{
std::cerr << "Could not properly close file: " << filename << "\n";
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
There is no need to use a char[]. You've even #included string so just use that.
string fileName;
cout << "Enter the name of the file you would like to open: ";
cin >> fileName;
// or
// getline(cin, fileName);
ifstream infile(fileName);
if (infile.fail()) {
exit(EXIT_FAILURE);
}
string line;
while (infile >> line) {
cout << line << " ";
}
system("pause");
return 0;
I also modified a few things to make it a bit cleaner.
Thanks for the help. Yes the file was in the wrong folder. It was a newb oversight!

Why isn't my input stream opening my file? C++

I'm reading in a file name from the keyboard and opening the specified file. However it is not meeting my if statement that determines if it's open or not. Heres my code:
#include "prog.hh"
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
string fileName;
cout << "Enter the file name to be read: ";
cin >> fileName;
ifstream input_file("fileName");
std::string line_; // string which text file contents will be stored in
if(input_file.is_open()){ // validation to see if the file is open
while(getline(input_file, line_)){
std::cout<<line_<< '\n'; //prints the contents of the file into the console
}
input_file.close();
}
else {
std::cout<<"File is not open"<< '\n';
}
std::cin.get();
After being compiled, I type in the file name I want to open and I get back the else message "File is not open", although the ifstream should of opened it. I definitely have the right file I'm trying to open in the correct folder. Any help appreciated, thanks.
change
ifstream input_file("fileName");
to
ifstream input_file(fileName);

can't open file ,mystate for datafile2 =2

When I debug this I can see it opens datafile1 , it reads the firstline and
in the logfile I get roma-3-4.log
It change to c:/temp/roma-3-4.log but when I want to open it , it fails. I have check that the _Mystate = 2 .
What is the meaning of that
Thanks
in the transfersubs.cfg there is this
roma-3-4.log
** In the directory c:/temp/ I have the following file
roma-3-4.log
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
using namespace std;
int main()
{
string input;
string logfile;
string errorfile;
short logfilesize1;
fstream dataFile1("c:/temp/transfersubs.cfg", ios::in);
if (dataFile1)
{
getline(dataFile1, input, '$');
logfile=input;
logfilesize1=input.size();
errorfile=input;
errorfile[logfilesize1-4]='e';
errorfile[logfilesize1-3]='r';
errorfile[logfilesize1-2]='r';
logfile="C:/Temp/"+logfile;
fstream dataFile2( logfile, ios::in);
if (dataFile2)
{
dataFile2.close();
}
else
{
cout << "ERROR: Cannot open logfile.\n";
}
dataFile1.close();
}
else
{
cout << "ERROR: Cannot open file.\n";
}
system("Pause");
return 0;
}
I believe your getline doesn't bother looking the newline but only for a $. You didn't post the file you are reading from, but check to ensure it has a $ at the end of the file name otherwise it will fetch the entire file.
It appears that unless you put a \n or endl after writing to the file using ofstream, ifstream won't be able to read anything from the file. In fact, adding a space after whatever you've written into file won't help either.
So always add a newline right after whatever it is that you've written to file using ofstream.