Writing On Text File C++ - 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);

Related

text file is not being opened for reading purposes

Before you flag this as a duplicate post and refer me on how to correctly open a text file and print to the console, I have looked at numerous StackOverflow posts about this topic and cannot find a solution for myself.
I am trying to open a text file I created (currently in the same project folder as my main.cpp), read the text, and print it to the console. I go through the if file is open statement fine but the while loop does not go through even once. I will post the function below. Please suggest any changes or ideas on how to correctly call and open/read the text file. (and I would prefer not to call the exact file location of the text file for this to work ex. C://example/textFile.txt/ Though I have not tried this method yet, I'd prefer avoiding it)
Also, I am using CLion IDE from jetbrains, C++17, and Ninja to build.
printing text file to console fucntion
#include <iostream>
#include <iomanip>
#include <iomanip>
#include <fstream>
#include <string>
#include <stdlib.h>
#include "printTest.h"
void printTest::print() {
std::string line; //string that holds the line of a text file
std::ifstream textFile("test.txt", std::ios::in); //file creation
if(textFile.is_open()) //checking if file was opened
{
while(std::getline(textFile, line))
{
//std::getline(textFile, line);
std::cout << line << "\n";
}
} else { //this is always printing i.e. file is not correctly being opened for reading
std::cout <<"Unable to open the text file..." <<std::endl; //Prints if file was not opened
}
textFile.close();
}

Why could file not be opened using ifstream?

I'm trying to create a simple terminal program that generates random Japanese Gojuōn. I have a source file, named "source", which looks something like this:
A I U E O
Ka Ki Ku Ke Ko
...
あ い う え お
か き く け こ
...
Now, I'm trying to read each line of content into a string variable, and print it out onto the screen, but I was not able to open the file. Here is my code:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
ifstream source ("source");
string line;
if (source.is_open())
{
while (getline(source, line))
{
cout << line << "\n";
}
source.close();
}
else cout << "Unable to open file!\n";
}
When I ran the code on terminal, I got "Unable to open file!". The code was in the same directory as the source file.
Are you running from inside your IDE? This is a very common thing when using an IDE.
The current working directory when running from the IDE may not be what you think it is. Try changing the path to the file to be the absolute path so you KNOW it's finding it.

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.

How to use file strings as commands in c++

I am trying to make a program on Windows 10 using Visual Studio 2015 that would sim-link certain files to certain locations. I am trying to make a text file with the location of the files, and the sim-link destination to use.
This is an example of the file data that would be in the properties.txt file:
FileLocation: "Z:\Folder\file.txt"
FileMkdirLocation: "Z:\Folder2\file.txt"
I want to use something like system(mkdir "sim-link_file_location" "file_location") by changing the data that is in properties.txt. I want to be able to add more than 1 file, without recompiling the program and writing each command for each file, one by one.
The problem is that I don't know how to make the commands use the data in the file.
EDIT: I managed to find out a way, but I get errors when compiling the program. I use this code:
#include <iostream>
#include <fstream>
#include <string.h>
#include <stdlib.h>
using namespace std;
//initialization of Properties File used
ifstream PropertiesFile ("PropertiesFile.txt");
int main()
{
//initialization of variables used
int input_option;
char FileLocation[256], Command[]="mklink ";
// string FileLocation, Command;
PropertiesFile >> FileLocation;
/* switch (input_option)
{
case "add all mods":
}
*/
cout << "FileLocation: " << FileLocation;
cout << endl;
strcat(Command, FileLocation);
Command[strlen(FileLocation)] = '\0';
cout << Command;
cout << endl;
//system(command);
system("pause");
return 0;
}
I know that i haven't used all variables yet.
It tells me that "strcat" is deprecated and to use "strcat_s" instead, and when i replace it with that, I get
"Debug Assertion Failed - Expression: (L"Buffer is too small" && 0)"
I had to make the "Command" char bigger than "FileLocation" because then strcat_s would not be able to copy the content. After that the program worked fine, and there were no other Assert Errors.
The command to create a soft link in linux is: ln -s <source> <destination>
You can use this in a system(""); call, BUT before you continue in your code, you will have to make sure that the kernel finished executing this command.
After that you can read the link as if it was the original file.

C++ code not finding file

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.