Not able to write to a file - c++

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\

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.

how do I load a file for c++ on mac

I am trying to load my file with C++ using ifstream, however it just wouldn't work. I use Atom with Xcode as compiler on my Mac.
This pops up:
dyn3180-214:~ joshua$ /var/folders/y6/jrfdjlsx0nqcxyfvsrfw6bnw0000gn/T/excersice ; exit;
file was not opened correctly
logout
#include <iostream>
#include <fstream>
#include <cstdlib>
int main(){
std::ifstream infile;
infile.open("numbers.txt");
if(!infile.is_open()){
std::cout<<"file was not opened correctly"<<std::endl;
exit(EXIT_FAILURE);
}
int n;
while(infile>>n){
std::cout<<n<<std::endl;
}
return 0;
}
Read how to debug small programs and also the documentation of GDB (or of whatever debugger you have on your machine).
Compile your program (that is the C++ file, let's name it josh.cc, shown in your question) with all warnings and debug info. I recommend to compile it on the command line with g++ -Wall -Wextra -g josh.cc -o joshprog (read how to invoke GCC for details) then to debug it with gdb ./joshprog and to run it in a terminal as ./joshprog.
The point is that your IDE (Atom + XCode) is not helping you. It hides you important details (see this answer, it also works for MacOSX or other Unix systems). That is why I strongly recommend compiling (and running, and debugging) your code with explicit commands that you are typing in a terminal emulator for your shell and understanding (so read the documentation of every command that you are using). Once you are fluent with compilation on Unix systems, you might eventually switch to an IDE (but you need to understand what your IDE is doing on your behalf, and what commands it is running).
You could add into your code something displaying the current working directory by using getcwd (which requires #include <unistd.h> on POSIX system), maybe something like
char mycwdbuf[80];
memset (mycwdbuf, 0, sizeof(mycwdbuf));
if (getcwd(mycwdbuf, sizeof(mycwdbuf)-1) != NULL)
std::cout << "current directory is " << mycwdbuf << std::endl;
By doing that, you'll probably understand how is your program started and in which working directory. I guess that it was not started in the working directory that you wanted it to.
In Xcode, select the project navigator, then click on your project. This will open the project editor. Select the Build Phases tab. Open the dropdown for Copy Files. Set Destination to Products Directory. Add a Subpath if you have to. Drag the necessary files into the project editor or add them via +.
Example: During the build phase, project files associated with the target will be copied to the designated subpath in the directory within the Products directory.
I think, Xcode generating the .o (object file ) file in different directory, and your .txt is present in different directory. I do code in Xcode, it always generate the .o file in different directory.

File path issue in C++ program when executing from a shell script on Linux [duplicate]

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

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.

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