Passing a value while writing inside a file:C++ - c++

I need to pass the value of one of the variables(containing the value of a path) to the contents of the file I am writing. The file outfile is of type ".ctl"
Lets say the file "outfile.ctl" gets created at location /abc/xyz
so I will be having /abc/xyz/outfile.ctl at this location. Now inside outfile.ctl file I have written some context. If you see the contents carefully I have included the line: file <<"file='filepath/Trial.data'\n"; which creates another file with the name Trial.data in the location filepath.Lets says filepath = /pqr/stu. So Ideally after the outfile.ctl file compiles I should have trial.data created at /pqr/stu llocation. I want to achieve this by the system command. But not getting the desired result created.Elaborated code is below
Snippet of the code.
void somefunc()
{
fstream file_1;
char outfile1[120],
filename[50] = "/abc/xyz/outfile.ctl";
char filepath[50] = "/pqr/stu/;
strcpy(outfile1, filename);
cout << outfile1;
cout << "\n";
file_1.open(outfile1, ios::out);
if (file_1) {
file_1 << "export\n";
file_1 << "client=000\n";
file_1 << "file='" << filepath << "/Trial.data'\n";
file_1 << "delete from BDRGIN\n";
file_1 << "select * from BDRGIN\n";
file_1.close();
system("R3trans outfile1");
}
Ideally the last line should create the trial data file in /pqr/stu/ folder but it doesnt. In my case it doesnot happen so , and a file outfile_1(without file extension) gets created in the folder where I am running the .cpp script. Can someone help?

It's not hard
file << "file='" << filepath << "/Trial.data'\n";
In C++ variables don't get substituted inside strings (unlike some scripting languages).
EDIT
You have basically made the same mistake again with your system command, variables don't get substituted inside strings. If you need a string variable which is made from other string variables you have to build up the string using strcpy and strcat. Try it like this
char cmd[250];
strcpy(cmd, "R3trans ");
strcat(cmd, outfile1);
cout << cmd << "\n"; // for testing
system(cmd);

You are missing a couple of things which I added:
You didn't include the output filename and filepath variables into your code, you didn't post all of your code to make in compilable.
Below is the code with "current path" (which we obtain with cwd in Linux) and your filename, included into your file "Trial.data" and written to the "current path/Trial.data" in you compile directory.
#include <iostream>
#include <fstream>
#include <string.h> //for strcat to concatinate the two (filepath+filename)
#include <unistd.h> //for getcwd to obtain your 'current path'
using namespace std;
int main(){
fstream file;
char cwd[256];
char *filepath= {getcwd(cwd, sizeof(cwd))}; // or write your path here instead
char filename[15] = "/Trial.data";
strcat(filepath, filename);
file.open(filepath,ios::out);
if(!file){
cout<<"File creation failed";
} else {
cout<<"New file created";
file <<"export\n";
file <<"client=000\n";
file <<"file='" << filepath << "'\n";
file <<"select * from HTTPURLLOC\n";
file.close(); // Step 5: Closing file
}
return 0;
}

Related

How do I output into a file in subdirectory?

This is not a duplicate. I'm trying to print some output to a file in a subdirectory (in this case to a file /stuff/output_1.txt) but it doesn't seem to create any new file. The code executes but no file is created, nor any subdirectory called /stuff. Here is my code:
#include <iostream>
#include <sstream>
#include <fstream>
using namespace std;
int main(void)
{
int out = 1;
stringstream fname;
fstream f;
fname << "./stuff/output" << "_" << out << ".txt";
f.open(fname.str().c_str(), ios_base::out);
f << "hello" << "\t";
f << endl;
f.close();
}
When I instead use the line
fname << "output" << "_" << out << ".txt";
It creates a file called output_1.txt in the current directory so the rest of the code clearly works. What is going wrong?
I'm on macOS so the "/" should be correct instead of the "\" used on Windows, no?
no file is created, nor any subdirectory
You are using fstream which expects the path to exist. If you are referencing a directory and it doesn't exist, then it will fail, because either you have to create the directory before you run your program, or you have to use mkdir() to create it.
You can check with f.is_open() if your stream could be opened.
f.open(fname.str().c_str(), ios_base::out);
if (f.is_open())
{
f << "hello" << "\t";
f << endl;
f.close();
}
else
std::cerr << "Unable to open " << fname;
nor any subdirectory called ./stuff
Why did you expect fstream to create subdirectories for you ? You have to do that yourself. I got the same behaviour when testing it on my machine, and the simple solution was to do a mkdir stuff. After that, the file got correctly created. But I think it's weird no runtime error is thrown. It's not good (especially for beginners) that fstream jsut silently does nothing when the subdirectory is not existing.

How to open a text file

I am trying to open a text file, and the code below is my attempt:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
std::ifstream file;
file.open("InputFile.txt");
std::string fileOutput;
if (file.is_open())
{
while (!file.eof())
{
file >> fileOutput;
std::cout << fileOutput << std::endl;
}
}
else
{
std::cout << "File failed to open" << std::endl;
}
file.close();
return 0;
}
The text file is located on my desktop, and it only contain two integers.
Whenever I run the code above, it will show me the "file failed to open" message. I am completely new to c++, so I really don’t have any idea why my code is not working. So any comments would be appreciated.
The text file is located on my desktop
So where is your C++ source file, is it located in my desktop as well?
Note this code file.open("InputFile.txt"); tries to open the InputFile.txt in the current folder, that means it only works if both C++ source file and your text file are in the same folder. That seems to be your problem.
Like #ShadowRanger's this comment, the existing answers are both inaccurate. The argument for file.open() needs to either 1. reflect the relative location of the text file in relation to the current working directory (where you are calling the executable from), or 2. give the absolute location of the text file on the disc.
I suggest the following solution:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main(int argc, char** argv) {
if (argc != 2) {
std::cout << "incorrect number of inputs" << "\n";
std::cout << "correct usage: this_executable.exe file_location" << "\n";
return -1;
}
std::ifstream file;
file.open(argv[1]);
std::string fileOutput;
if (file.is_open())
{
while (file >> fileOutput)
{
std::cout << fileOutput << std::endl;
}
}
else
{
std::cout << "File "<< argv[1] <<" failed to open" << std::endl;
}
file.close();
return 0;
}
This solution takes the file's address info out of the code. With this solution, when you call your executable, the file's address(directory path + file name) is given to the executable at run-time rather than compile-time. Now, you'd run the executable like:
C:\path_to_your_exe>my_executable.exe C:\path_of_your_txt_file\InputFile.txt
The benefits of this approach are:
You can change the file's name / path without having to recompile the code;
On the commandline, it is easier to check that the target file's address is correct by tab completion
Also note:
As #ShadowRanger also pointed out the Why is “while ( !feof (file) )” always wrong? issue which I was not aware of.
If you are wondering what argv[1] means, see this guide for more information on commandline arguments for C++. You also want to make sure to catch situations when the user did not specify an input (meaning argv[1] is invalid, thus the argc != 2)
Unless the file you are opening and your executable are in the same directory, the same message will be printed since it will search for the file in the current working directory. You can specify the absolute path to the file on your desktop using %USERPROFILE%\\Desktop\\InputFile.txt or any other environmental variable that maps the absolute path of a disk, from which your file can be found.

Why doesn't this open the file in the directory of the program?

I have this short program:
#include <cstdlib>
#include <iostream>
#include <fstream>
#include <string>
int main (int argc, char * argv[]) {
std::string homedir = std::getenv("HOME");
std::string filename = argc > 1 ? argv[1] : (homedir + "/" + "file");
std::cout << homedir << std::endl;
std::cout << filename << std::endl;
std::fstream file;
file.open(filename, std::ios::out);
file << "Yo yo waddup" << std::endl;
file.close();
return 0;
}
When I supply no arguments, it opens a file in the users home directory. That of course makes sense. But when I run it from a different directory like this:
$ ./folder/hometest examplefile
The program creates "examplefile" in my current directory instead of the directory where the program is.
Why exactly is this happening?
Why exactly is this happening?
The program is behaving just as expected.
The file is opened relative to the current work directory, not where the executable is located.
If it didn't work that way,
All your programs will have to work with absolute paths, or
The location of the program will be flooded with files. First, that might not be possible because of permissions issue. Second, in a multi-user system, users will end up trying to create the same file names/directories.
Neither of the above is desirable.

I am trying to read in multiple files from a directory and use them in my program before moving on to other files in the directory

I have a directory with 188 files in it that look something like this.
001_AU01_query.dat
001_AU12_query.dat
001_AU17_query.dat
001_template.dat
002_AU01_query.dat
002_AU12_query.dat
002_AU17_query.dat
002_template.dat
This repeats all the way to 047_AU
What my program needs to do is take in one query file and the corresponding template file i.e.(use the 001_AU01_query.dat with the 001_template.dat file) and run through the code. Then use the next 001_AU file with the same template file. This will repeat all the way to 047.
I can manually put in one query file and one template file and it works fine. I just do not know how to go about using all files in the directory.
int main(int argc, char *argv[])
{
string outFileName = "";
string templateFile = "";
string queryData = "";
ofstream outStream;
Scanner inStreamTemp;
Scanner inStreamQuery;
calc calc;
Utils::CheckArgs(3, argc, argv, "queryData templateFile outFileName");
queryData = "data_project_part1/001_AU01_query.dat";
templateFile = "data_project_part1/001_template.dat";
outFileName = "outFile";
Utils::FileOpen(outStream, outFileName);
if (Utils::FileDoesNotExist(queryData)||Utils::FileDoesNotExist(templateFile))
{
cout << "ERROR: query data file or template file name does not exist" << endl;
exit(0);
}
inStreamQuery.openFile(queryData);
inStreamTemp.openFile(templateFile);
calc.initialize(inStreamQuery, inStreamTemp);
calc.runComputation(outStream);
outStream << "Query File: " << queryData << "\n" << "Template File: " << templateFile << "\n" << "The ten closests neighbors are:\n" << calc.toStringResults() << "\n" << endl;
outStream.flush();
Utils::FileClose(outStream);
return 0;
}
One way to do it is to put your file names in a list and loop through that list.
You can put those names in a list by copying and pasting them to a text editor, save in notepad, read line by line and add to a list .
Then loop through that list and read from each one using a foreach loop

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;
}