Can't open txt files in c++ program with Visual Studio 2019 - c++

I just started using Visual Studio 2019 after using XCode for a while.
I was always able to open txt files in XCode but now
I can't open them in Visual Studio 2019.
Basically what I do is I press "Start Without Debugging" in the "Debug" tab I and get the error message "File Did Not Open!" from the else statement that I wrote. I am not sure if it has something to do with where the txt file is located or with the file path.
Below is the simple program that I've so far been using
to figure out how to open txt files in Visual Studio 2019:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
ifstream fobj;
fobj.open("input.txt");
if (fobj)
{
cout << "File Opened!\n";
}
else
{
cout << "File Did Not Open!\n";
}
return 0;
}

You are using a relative file path to open the file. The calling process' "current working directory" is likely not what you are expecting (check with GetCurrentDirectory() to verify). Always use absolute file paths when opening files.
For instance, if the file is in the same folder as your EXE, use GetModuleFileName() to get the EXE's full path, then replace the filename portion with your desired filename:
#include <iostream>
#include <fstream>
#include <string>
#include <windows.h>
#include <shlwapi.h>
int main()
{
char filename[MAX_PATH] = {};
::GetModuleFileNameA(NULL, filename, MAX_PATH);
::PathRemoveFileSpecA(filename);
::PathCombineA(filename, filename, "input.txt");
std::ifstream fobj;
fobj.open(filename);
if (fobj)
{
std::cout << "File Opened!\n";
}
else
{
std::cout << "File Did Not Open!\n";
}
return 0;
}

Related

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");

opening an ifstream file in C++

#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main() {
string txt="";
ifstream file;
file.open ("ernio.txt", ios::in);
if (file.is_open()) {
while (getline(file, txt)) {
cout << txt << endl;
}
}
else
cout << "example" << endl;
return 0;
}
It prints example instead of reading line by line from the file. What am I doing wrong?!? (the file is in the exact same place as the main.cpp) We even tried:
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main() {
string txt="";
ifstream file("ernio.txt");
if (file.is_open()) {
while (getline(file, txt)) {
cout << txt << endl;
}
}
else
cout << "example" << endl;
return 0;
}
Please help
The file needs to be in the directory from where the executable will be called, not in the source directory where your main.cpp resides.
When you build small programs with gcc or something similar from the command line, often the executable is in the current working directory, where the compiler will also draw the source files from.
When using a build system or an IDE, however, then usually the target of a build is different from that where the sources reside.

Opening a txt.file in c++

I'm trying to open a simple txt.file in c++ (visual studio), but are only triggering "else".
codes.txt is together with the main file in source files and are included. This is more or less how it looks
#include <iostream>
#include <fstream>
int main()
{
std::ifstream file("codes.txt");
if (file.is_open())
{
std::cout << "success" << std::endl;
}
else
{
std::cout << "Unable to open file" << std::endl;
}
}
The txt file did not exist in the folder of the program. Runned perfectly after it was included.

Why does this code fail to read Blender's .obj file?

Hi I am trying to read a Wavefront file which was created using Blender. I put a copy of this file into the solution Explorer. When I tried to compile for the first time I got the following message:
fatal error LNK1107: invalid or corrupt file: cannot read at 0x...
It seemed like the compiler confused Blender's .obj files with some other format which also uses the .obj ending. The solution was to exclude the file from the build process in its properties.
Now the application does compile but there is no data displayed like I would expect it. Not sure if this is a code issue.
#include "stdafx.h"
#include <iostream>
#include <stdlib.h>
#include <fstream>
#include <string>
using namespace std;
void ReadPrintFile(string _fileName)
{
std::string line;
std::ifstream fileStream (_fileName);
if (fileStream.is_open())
{
while (getline(fileStream,line))
{
cout << line << '\n';
}
fileStream.close();
}
else
{
cout << "Unable to read file";
}
}
int _tmain(int argc, _TCHAR* argv[])
{
ReadPrintFile("Drone.obj");
std::cin.get();
return 0;
}
The code does not jump into the else statement. The filestream simply seems to be empty and I am directly forwarded to the cin.get(); statement. I know that there are tons of tutorials on how to parse .OBJ in C++ but I want to understand.
The trick was not to copy the file into the solution explorer but into the project folder.

C++ Trouble Reading a Text File

I'm trying to read a text file but nothing is coming out. I feel like maybe It's not linking correctly in my Visual Studio Resources folder but if I double click it - it opens fine in visual studio and it doesn't run into any problems if I test to see if it opens or if it is good. The program compiles fine right now but there's not output. Nothing prints to my command prompt. Any suggestions?
Code
#include <iostream>
#include <iomanip>
#include <fstream>
using namespace std;
int main()
{
char str[100];
ifstream test;
test.open("test.txt");
while(test.getline(str, 100, '#'))
{
cout << str << endl;
}
test.close();
return 0;
}
Text File
This is a test Textfile#Read more lines here#and here
You try to open file by name without path, this means the file shall be in current working directory of your program.
The problem is with current directory when you run your program from VS IDE. VS by default sets current working directory for runnning program to project directory $(ProjectDir). But your test file resides in resources directory. So open() function could not find it and getline() immediately fails.
Solution is simple - copy your test file to project directory. Or copy it to target directory (where your program .exe file is created, typically $(ProjectDir)\Debug or $(ProjectDir)\Release) and change working directory setting in VS IDE: Project->Properties->Debugging->Working Directory, set to $(TargetDir). In this case it will work both from IDE and command line/Windows Explorer.
Another possible solution - set correct path to file in your open() call. For testing/education purposes you could hardcode it, but actually this is not good style of software development.
Not sure if this will help but I wanted to simply open a text file for output and then read it back in. Visual Studio (2012) seems to make this difficult. My solution is demonstrated below:
#include <iostream>
#include <fstream>
using namespace std;
string getFilePath(const string& fileName) {
string path = __FILE__; //gets source code path, include file name
path = path.substr(0, 1 + path.find_last_of('\\')); //removes file name
path += fileName; //adds input file to path
path = "\\" + path;
return path;
}
void writeFile(const string& path) {
ofstream os{ path };
if (!os) cout << "file create error" << endl;
for (int i = 0; i < 15; ++i) {
os << i << endl;
}
os.close();
}
void readFile(const string& path) {
ifstream is{ path };
if (!is) cout << "file open error" << endl;
int val = -1;
while (is >> val) {
cout << val << endl;
}
is.close();
}
int main(int argc, char* argv[]) {
string path = getFilePath("file.txt");
cout << "Writing file..." << endl;
writeFile(path);
cout << "Reading file..." << endl;
readFile(path);
return 0;
}