C++ code not finding file - c++

I'm trying to create a program that will concatenate (add two lists of integers together)
each list is stored as a text file. I want the C++ program to open list1.txt and list2.txt
I can't actually get it to work though. I've put two lists of integers names list1 and list2 respectively however I'm getting the output cannot find list1.
#include <iostream>
#include <fstream>
#include <ostream>
using namespace std;
int main()
{
ifstream findlist1("list1.txt", ios::in | ios::binary);
if(!findlist1)
{
cout << "Cannot find list 1.\n";
return 1;
}
ifstream findlist2("list2.txt", ios::in | ios::binary);
if(!findlist2)
{
cout << "Cannot find list 2.\n";
return 1;
}
ofstream out("list3out.txt", ios::out | ios::binary);
if(!out)
{
cout << "Unable to output file ";
return 1;
}
out << in1.rdbuf();
out << " " << flush;
out << in2.rdbuf();
return 0;
}
EDIT = SOLUTION:
My files were called test1.txt and were therefore showing up to the program as test1.txt.txt

The code looks fine, you may try using absolute path or put the files in the same directory of executable

If you are using Visual Studio, all relative paths are relative to the project's working directory. The default seems to be the project directory - meaning that if in C:\SolutionX\ProjectY\Build\ProjectY.exe you try to open the path "file.txt", Windows will look for C:\SolutionX\ProjectY\file.txt. If you'd like to change this directory, the setting is in the project's Configuration Properties under Debugging as "Working Directory".
Note that if you double click the executable manually rather than running it through Visual Studio, its working directory will be its current location. If instead you run the program from a command line, the working directory will be your working directory in the command line.

Related

ifstream won't find file even though it's in the same directory

I've got a method to read a vector of bools from a file:
std::vector<bool> OPCConnector::getAlarmVector() {
std::vector<bool> data;
std::ifstream DataFile(filepath);
if (DataFile) {
bool value;
while (DataFile >> value) {
data.push_back(value);
std::cout << value;
}
}
return data;
}
The filepath variable is an object property that is assigned through the constructor:
OPCConnector::OPCConnector(std::string fpth) {
filepath = fpth;
}
And in the main() function, the constructor is called:
std::vector<bool> activations;
std::string filepath = "alarmes.txt";
OPCConnector opcc = OPCConnector(filepath);
activations = opcc.getAlarmVector();
Now, I've checked what the folder of the executable is via GetModuleFileNameA(), and I made sure that the file is in the same directory and has the same name (also, I made sure that the extension isn't part of the file name, like "alarmes.txt.txt").
I debugged the first method getAlarmVector() and it never gets past the if (DataFile) condition, as if it won't find file.
I run the code using Visual Studio 2019, and nothing happens. The vector remains empty. Error is No such file or directory.
Default working directory is $(ProjectDir) and it's exactly where my file is.
Edit: I've also tried using both relative and absolute paths, none work.
Edit 2: I've also checked the directory using GetCurrentDirectory() and copied the .txt file there too, and it isn't working.
SOLUTION: Strangely enough, I deleted the file and created it again with the same name, and it worked. Thanks for the answers.
My guess: your current working directory isn't what you think it is, especially if you're running from an IDE. I know of several IDEs where the current working directory is some build directory (it varies by IDE) unless you specifically change it.
I'm fairly sure Visual Studio is one such IDE.
Here's a tiny example program I wrote;
$ cat Foo.cpp
#include <iostream>
#include <fstream>
int main(int, char **) {
std::ifstream file { "Foo.cpp" };
if (file) {
std::cout << "File opened.\n";
}
else {
std::cout << "File not opened.\n";
}
}
Compile and run it:
$ g++ --std=c++17 Foo.cpp -o Foo && Foo
File opened.
Current folder and folder-of-exe-file are different things (sometimes). Try to specify full name of file (with disk, all folders, etc.).
You can check errors of file open operation by calling
if (!DataFile) { ... }
The std::filesystem library can help you resolve file and path related issues.
#include <filesystem>
// (in some function)
std::filesystem::path filepath = "alarmes.txt";
if ( !exists(filepath) )
{
std::cout << "File path " << filepath << " at absolute location "
<< absolute(filepath) << " does not exist\n";
}
See it on Compiler Explorer
You can get an error code (and get a description of error in internet) if you use C-function fopen. If open is failed, you get the nullptr as result of fopen and errno will contain code of error.

Errors in relative path

So this is a simple C++ program for reading a file and displaying its contents.
My directory structure is as follows
Project Directory
|
Data___
| |
| data.txt
|
program1.cpp
and The program:
#include <iostream>
#include <fstream>
using namespace std;
int main () {
char char1;
fstream data; // Because I wanna to write to this file later.
data.open("../Data/data.txt",ios::out | ios::in);
if (data.is_open()) {
for (int i = 0; !data.eof(); ++i) {
data.get(char1);
cout << char1 << endl;
}
data.close();
}
return 0;
}
So currently my program works fine... However when I use:
data.open("Data/data.txt",ios::out | ios::in);
The program doesn't work. Why is this so? Ideally the above mentioned code piece should work since the Data folder is in the same directory as my cpp file.
data.open("../Data/data.txt",ios::out | ios::in);
By using 2 dots we are going back a directory and the Data folder isn't there.
Then why is the program working using the 2 dots?
Looking at your directory structure, I see that both your program1.cpp and data.txt are in the same "Data" folder. Since you are already inside the Data folder, "Data/data.txt" looks for another Data folder. In UNIX ".." means the previous directory. So when you use ".." you go to "Project Directory", which contains a "Data" folder. That is why data.open("../Data/data.txt",ios::out | ios::in) is working. You can also try using the following:
data.open("data.txt",ios::out | ios::in);

Unable to open file.txt with c++

I've looked up similar posts here, but none seem to be doing the job for my question. I'm basically trying take a sequence of words in a .txt file and put each word in a vector, and printing each value afterwards. For example, we have I love racing cars in array.txt, and I want my vector to have "I" at position 0, "love" at 1 and so on. Unfortunately, the code does not access "array.txt", so it never executes the code in the if condition.
Now I've heard that by using the fstream library it should work just fine, but the file is never found. I suspect that it doesn't work because it cannot find the path, but I have never opened files in C++. Also, I have not put my file anywhere in my project folder.
Some changes I've already tried:
file.open("array.txt");
omitting file.close();
include "C:\array.txt"; (with the # in front)
file.open("C:\array.txt")
And I'm using Windows 10, if this matters.
#include <iostream>;
#include <string>;
#include <vector>;
#include <fstream>;
//#include <"C:\Users\Samer El-Hage\Documents">;
using namespace std;
void main(){
vector<string> v (10);
ifstream file;
file.open("C:\array.txt", ios::in);
if (file.is_open())
{
for (int i = 0; i < 3; i++)
{
file >> v[i];
}
file.close();
}
else cout << "Could not access file.";
for (int i = 0; i < 3; i++)
{
cout << v[i] << " ";
}
}
This code prints "Could not access file."
The file cannot be opened because the file system can't find the file named "[Bell]rray.txt". the character sequence '\a' is the "Make my computer Beep" character.
Use either forward slashes: "C:/array.txt", an escaped backslash: "C:\\array.txt" or a raw string literal: R"(C:\array.txt)"
The file must also exist at the specified location. If you do not provide a drive and just say "array.txt" the location defaults to wherever the executable is (or in an IDE, the Working Directory).
Also, you have unnecessary semi-colons after your includes. (In fact, in a Treat Warnings as Errors setup, this won't compile!)
I got it! I had not put the .txt file in my folder with the source code, which, strangely enough, was not mentioned in my previous search results... I got to search better!
\a simply turns the computer beep on. Try writing "C:\\array.txt" instead in the open call.
Try not calling open explicitly:
ifstream file ("array.txt");
Look at the examples here:1

ofstream does not create file when running with CLion using CMake

I have this code to create a file, when I run it with CLion it prints out to the console but does not create file, how can I fix this? thanks
#include <iostream>
#include <fstream>
using namespace std;
int main() {
ofstream log_file;
log_file.open("sample23.txt");
if (log_file.is_open())
std::cout << "Open";
log_file << "stuff" << endl;
log_file.close();
return 0;
}
The file may be created into another directory (the working directory).
You can find that location (and change it if needed) as indicated here:
How do I change the working directory for my program
make sure to flush before closing because file is empty
try this out
ofstream f;
f.open( "sample.txt", ios::out );
f << flush;
f.close();
3 things here:
1.) In order to output to another file, you must make another variable like this:
ifstream someoutputfile;
someoutputfile.open("filename");
2.) you actually must make another variable to be "placeholder" of sorts that will automatically assign the first thing your file finds and assigns that to. This may depend on what datatype (int, double, string etc) your input file consists of. Instead of:
log_file << "stuff" << endl;
you can do something like this...
// if my input file is integers for instance..
int data = 0;
log_file >> data;
This can also work for if your file contains multiple data types.
ex:
// if I have two different data types...
string somebody;
int data = 0;
log_file >> data >> somebody;
3.) to output your file data to the screen, just follow a similar way as the example in #1.
someoutputfile << data << somebody << endl;
in addition, dont forget to close the data of BOTH your input and output files:
someoutputfile.close()
Hope that helps in some way :)

Writing On Text File C++

I am simply trying to get a program to write "Test" to a created file. However, when I run the code below there is no file in the working directory. I am running this code on a Mac and compiling using gcc from Terminal.
// writing on a text file
#include <iostream>
#include <fstream>
using namespace std;
int main () {
ofstream myfile ("example-1.txt");
if (myfile.is_open())
{
myfile << "This is a line.\n";
myfile << "This is another line.\n";
if (myfile.fail())
cout << "Fail" << endl;
myfile.close();
}
else cout << "Unable to open file";
return 0;
}
All the code I posted is valid and works. However, I was compiling via the command line on a Mac OSX using gcc. The command looks like this:
g++ -g nameofinputfile.cpp -o nameofoutput.out
This works fine, however when you open the .out file (compilation file) the example-1.txt file is created at the root of the Users file where Documents, Desktop, Downloads etc. exist. Simply you just have to state where it is to be created. Refer to this question to learn how to specify the directory in your code.
You must use of fprintf() for write text on text files.
For example :
fp1=fopen("report.txt","a+");
fprintf(fp1,"Port is open: %d\n\n",i);
fclose(fp1);