Output file to specific folder C++ Windows 7 - c++

I am using C++ and trying to output a file to a specific place, a folder with a specified name in the same directory as the executable. Couldn't find a great resource on an easy way to do this but I know it must be possible.
My example. I am saving a log file and instead of having it save to the same directory as the executable, it saves to /logs/
Thank you for your time!
Edit: I used mkdir to create a folder but how do I output to that folder. Is mkdir even a good thing to be using? I want to learn the best way to do this, not necessarily the easiest.

This code:
#include <fstream>
#include <iostream>
int main() {
std::ofstream of( "C:\\mydir\\somewhere\\log.txt" );
of << "hello\n";
}
will write "hello" to the file log.txt in the directory c:\mydir\somewhere, assuming the directory exists. And yes, mkdir is the right function to use. If you don't want to hardcode the path, you can find the path & name of the executable with GetModuleFileName, and then create the path programatically from that - see How to get Current Directory? for an example.

Related

How do you write a file in a specific location on iPhone?

I have been trying to create and write a file using an iPhone C++ compiler, but the file always ends up at a location called /tmp, which I do not have access to. Is there any way to use the iPhone to create and write a file to a specific path location?
I have tried to use the following code, but it does not create the file at that location:
#include <iostream>
#include <fstream>
int main(){
std::ofstream File("/private/var/mobile/Containers/Data/Application/8EDE34D7-84CE-4147-8126-8D1AF04717A1/Documents/my_folder/my_file.txt");
File << "Hello!";
File.close();
return 0;
}
Your code ignores state of your File object. It just blindly attempts to write into it so no one knows what went wrong when opening it. There are lot of things that can go wrong but you should add code to check its state on any platform.
Two most common things that can go wrong:
Is /private/var/mobile/Containers/Data/Application/8EDE34D7-84CE-4147-8126-8D1AF04717A1 certainly home directory of your app? You can not access files of another app, if you are trying to do that. Normally you should request your app home directory from operating system, with CFCopyHomeDirectoryURL or perhaps getenv works too:
std::string home = getenv("HOME");
If it is directory of your app then you still can not create files in directory my_folder if that directory inside Documents directory of your app does not exist. For that you need to use NSFileManager or perhaps mkdir from sys/stat.h works too.

Display files contain inside a particular directory by using C++ in LINUX

I'm working on assignment for my university. I have a question on how to display all the files contain inside a particular directory. My working environment is on LINUX UBUNTU 14.04 G++ Compiler.
Let's take an example, I want to display/output all the files inside this DIRECTORY
/home/user/Desktop/TEST/FileSystem
File contains inside FOLDER FileSystem
-test.txt
-abc.txt
-item.txt
-records.txt
I'm not sure whether it can be done by using:
-Using Execute System Command, by calling standard library header.
#include <iostream>
#include <stdlib.h>
int main()
{
system("pwd"); // Directory: /home/user/Desktop/TEST/FileSystem
system("ls"); // Display every files contain in the FileSystem Folder
}
OUTPUT that I expected:
/FileSystem Folder contains:
-test.txt
-abc.txt
-item.txt
-records.txt
How can I code my source code so that I'm able to achieving this OUTPUT/Display that I expected. I have go through some internet sources by googling it. But I find out difficulty on understand it. That's why I have made a decision to post my question on here.
Thank You in advance to you guys for helping me to solve my coding problem.
You need to first open directory for which you need to list files after that you need to read directory.
Add #include for using apis.
#include <dirent.h>
/* open the directory "/home/" for reading. */
DIR* dir = opendir("/home/users");
entry = readdir(dir)); //files or directories in /home
//Add logic to verify entry is file or directory
Refer this thread http://www.cpp-home.com/tutorials/107_6.htm
the function
system("ls")
is just firing the command but you are missing what the output of the command ls is.
You need to capture it.
In this other thread it's explained how to do it.

How do I use fstream to write to a file above the executable's directory in C++?

I'm trying to write to a file that is not in the directory that the executable is in; I also want it to work no matter where the executable is (I believe that would rule out using ".."). I need this to work on Linux. Thank-you.
This has been asked already, see Get path of executable or Finding current executable's path without /proc/self/exe for a good answer, or search yourself.
Your problem boils down to getting the absolute path to the running executable.
A relative path is usually resolved starting from the running directory, which is not necessarily the executable directory (rather the current directory in the shell from which the executable is launched).
Under linux, you can read the directory of the executable with:
readlink /proc/self/exe
or you could use boost fs::path and fs::system_complete. Then you have to remove from that string the last component, which is the executable name.
Once you have the path of the executable directory, append "/.." to it and you will get the directory above the executable directory.
You can use an absolute path, if you know it ahead of time:
fstream * fs = new fstream("~/config_file");
If the file varies, you can take the path from user input or a configuration file.
Depending on where the file is, whether it moves and where the program is, you may actually be able to use a relative path. From the info you've given, I couldn't tell.
You can do this easily, but you will have to have an absolute path to the file you want to work on, or you will have to create some relative file-structure between your executable and the file you are wanting to access.
Another option is you could, using a forked process or popen(), launch find, and give it the appropriate arguments to locate the document you are wanting to work on, and then use that returned string as the argument to create the fstream object to write to or append to that file.
So for instance, this could look something like:
#include <limits.h>
#include <fstream>
#include <stdio.h>
char buffer[PATH_MAX];
//search the entire file-system starting from the root for "my_specific_file.txt"
FILE* located_file_handle = popen("find / -name my_specific_file.txt -print", "r");
//get the first file returned from the find operation and close the pipe
fgets(buffer, PATH_MAX, located_file_handle);
pclose(located_file_handle);
fstream file(buffer);
If you think there will be more than one file returned from the call to find, then you should cycle though each of them using fgets until you locate the one you want.

Not able to write to a file

My programs have been running properly for over a year. Today I copied the files onto a different system and compiled every program.
When I compile and run from Dev-c++ it writes data onto a text file like its supposed to, but when I click on the executable it creates, it does not write data onto the file. Everything else like input/output seems to work.
What procedure have I missed?
Ok i've given the program Full permision but it still does not write.
I'm quite puzzled, atleast if it didn't run when i compile it in the C++ environment i can keep checking my code, but only the .exe does not work, any other suggestions ?
#include <iostream>
#include <fstream>
using namespace std;
int main() {
ofstream bss2;
bss2.open("expat.txt",ios::app);
bss2 << 2 ;
bss2.close();
}
This is the sample code i tested out.
How do i find the Current working directory ?
Ok i changed a line to
bss2.open("c:\\expat2.txt",ios::app);
and now it works properly in the exe file.
but there's over 50 files and i prefer i didn't have to spell out the new path to each one, what workaround is there to set the directory to the one previously used ?
update 4 :
#define _POSIX_SOURCE
#include <unistd.h>
#undef _POSIX_SOURCE
#include <stdio.h>
main() {
char cwd[256];
int y;
if (chdir("/tmp") != 0)
perror("chdir() error()");
else {
if (getcwd(cwd, sizeof(cwd)) == NULL)
perror("getcwd() error");
else
printf("current working directory is: %s\n", cwd);
}
scanf(y);
}
Ok i used the getcwd() and this is the message it gives me
chdir() error(): No such file or directory
How do i set the directory now.
Sounds like your working directory isn't being set correctly when you double-click on the file. If you can access a log, use getcwd() and log what it returns.
I don't have Raymond Chen's psychic debugging powers yet, but I do know of a tool that may help you: Process Monitor. Use it to see precisely which files your application is trying to write to, and why it fails.
Maybe your looking at the wrong location. The program will write the file to the current working directory, which may be different between when you double click on the executable and run from Dev-C++.
The best and easiest way is to give the full path of the output file rather than just the filename. That way, you can be sure where the file went, and not have to search for it everywhere. If you are using Windows, the output file might be somewhere in system32. But I could be wrong.
As others have said, the working directory is likely incorrect.
If you create a shortcut to the .exe, you can set the working directory in the shortcut properties. Right-click on the shortcut, select "Properties", and change the "Start in" property.
Of course a better answer is to put the full path of the file into the filename string when you open it.
It might be that Windows uses backslash, so try "\tmp" instead of "/tmp".
Also if all your files are in the same directory, then you can use find & replace and replace open(" with open("c:\\your_directory_here\

Directory of running program on Linux?

Hey, I've been writing a program (a sort of e-Book viewing type thing) and it loads text files from a folder within the folder of which the executable is located. This gives me a bit of a problem since if I run the program from another directory with the command "./folder/folder/program" for example, my program will not find the text, because the working directory isn't correct. I cannot have an absolute directory because I would like the program to be portable. Is there any way to get the precise directory that the executable is running from even if it has been run from a different directory. I've heard could combine argc[0] and getcwd() but argc is truncated when there is a space in the directory, (I think?) so I would like to avoid that if possible.
I'm on Linux using g++, Thanx in advance
EDIT - don't use getcwd(), it's just where the user is not where the executable is.
See here for details.
On linux /proc/<pid>/exe or /proc/self/exe should be a symbolic link to your executable. Like others, I think the more important question is "why do you need this?" It's not really UNIX form to use the executable path to find ancillary files. Instead you use an environment variable or a default location, or follow one of the other conventions for finding the location of ancillary files (ie, ~/.<myapp>rc).
When you add a book to your library you can remember its absolute path.
It is not a bad when your program rely on the fact that it will be launched from the working dir and not from some other dir. That's why there are all kinds of "links" with "working dir" parameter.
You don't have to handle such situations in the way you want. Just check if all necessary files and dirs structure are in place and log an error with the instructions if they are not.
Or every time when your program starts and doesn't find necessary files the program can ask to point the path to the Books Library.
I still don't see the reason to know your current dir name.
#include <boost/filesystem/convenience.hpp>
#include <iostream>
#include <ostream>
int main(int argc, char** argv)
{
boost::filesystem::path argvPath( argv[0] );
boost::filesystem::path executablePath( argvPath.parent_path() );
boost::filesystem::path runPath( boost::filesystem::initial_path() );
std::cout << executablePath << std::endl;
std::cout << runPath << std::endl;
return 0;
}
You can get the path of the running program by reading the command line. In linux you can get the command line by reading /proc folder as /proc/PID/CommandLine
argv[0] is not truncated when there are spaces. However, it will only have the program name and not the path when a program is run from a directory listed in the PATH environment variable.
In any case, what you are trying to do here is not good design for a Unix/Linux program. Data files are not stored in the same directory as program files because doing so makes it difficult to apply proper security policies.
The best way to get what you want in my opinion is to use a shell script to launch the actual program. This is very similar to how Firefox launches on Linux systems. The shell places the name of the script into $0 and this variable will always have a path. Then you can use an environment variable or command line argument to give your program the location of the data files, like this:
dir=`dirname "$0"`
cd "$dir/../data/"
"$dir/real-program"
And I would arrange your program so that it's files are somewhat like this:
install-dir/bin/program
install-dir/bin/real-program
install-dir/etc/config
install-dir/data/book-file.mobi