Opening a file in home directory - c++

Say you have a program you run, and it has the following lines of code:
#include <fstream>
using std::fstream;
int main() {
fstream someFile;
someFile.open("~/someFile");
if(!someFile.is_open()) {
// Make the file
}
}
I'm trying to open a file in the home directory (i.e. "~" on Unix devices). How could this be done? What I'm doing right now doesn't seem to work. Additionally, how can I make the file if it doesn't exist yet?
Note that this program can run from anywhere; not just home, but I need it to look for a file in the home directory.

open has a second parameter: openmode, so you may want something like
someFile.open ("somefile", std::fstream::out | std::fstream::app);
if you want to append.
For the home directory you can check HOME environment variable and getpwuid:
const char *homedir;
if ((homedir = getenv("HOME")) == NULL) {
homedir = getpwuid(getuid())->pw_dir;
}

Related

When my program runs automatically at startup, having trouble append text to file. Why?

I made a program that runs automatically at startup, but my program does not perform the task of append text to the file when it runs automatically.
Here example code:
#include <Windows.h>
#include <fstream>
#include <iostream>
void AutoRun() {
LONG key;
std::string FP;
char re[MAX_PATH];
FP = std::string(re, GetModuleFileNameA(NULL, re, MAX_PATH));
HKEY hkey;
key = RegOpenKeyExA(HKEY_LOCAL_MACHINE, "SOFTWARE\\Microsoft\\Windows\\Currentversion\\Run", 0, KEY_WRITE, &hkey);
if (key == ERROR_SUCCESS)
{
std::cout << "paketi yüklüyoruzzz";
key = RegSetValueExA(hkey, "testzort", 0, REG_SZ, (BYTE*)FP.c_str(), strlen(FP.c_str()));
RegCloseKey(hkey);
}
else {
std::cout << "Maga mapket müklenemedi:(: " << key;
}
}
int main(){
// open output file in append mode
const char* output_filename = "testing.log";
std::cout << "Logging output to " << output_filename << std::endl;
output_file.open(output_filename, std::ios_base::app);
AutoRun();
output_file << "zozozort\n";
}
When I restart my computer after execute this code, not add my file like:
zozozort
zozozort
What is the problem ?
NOTE: For the first time to run the regedit api, I ran the program with administrator mode when starting
First off, consider using HKEY_CURRENT_USER instead of HKEY_LOCAL_MACHINE (unless you really want all users of your machine running your app). And consider using KEY_SET_VALUE instead of KEY_WRITE (which includes rights you don't need in this code). This will reduce the need for your code to run as an admin when setting up the auto-run.
In any case, when calling RegSetValueEx(), you are setting the data size to strlen(FP.c_str()), which is wrong, as RegSetValueEx() requires the null terminator to be included in the data size:
If the data is of type REG_SZ, REG_EXPAND_SZ, or REG_MULTI_SZ, cbData must include the size of the terminating null character or characters.
So, use strlen(FP.c_str())+1 instead, or better FP.size()+1.
That being said, your app is opening the text file using a relative path, so its location is relative to the app's current working directory, which you don't know what it is when your app is started (you can use GetCurrentDirectory() to determine that). Just because the text file is in the same folder as your app doesn't mean the working directory points to your app's folder. Always use absolute paths when creating/opening files.
If you were using CreateFile() instead of (o)fstream (BTW, where is your output_file variable declared?) to create/open the file, then you could use GetFinalPathNameByHandle() to determine its actual full path, so you can see if it is what you are expecting.
If your really want to create/open the text file in your app's folder, you already know how to get the app's full file path from GetModuleFileName(), so simply replace the filename portion after the last '\' character with your text file's name, and then use that full path to create/open the file. Just make sure your app is not running in a folder that denies write access to non-admins, such as Program Files.
You really should be writing the text file into a folder that is guaranteed to be accessible to the calling user (preferably within their own profile), instead of in the app's folder. For instance, get a user-accessible folder path via either:
SHGetFolderPath(), specifying something like CSIDL_(LOCAL_|COMMON_)APPDATA, CSIDL_DESKTOPDIRECTORY, CSIDL_MYDOCUMENTS, etc.
SHGetKnownFolderPath(), specifying something like FOLDERID_(Roaming|Local)AppData, FOLDERID_ProgramData, FOLDERID_Desktop, FOLDERID_Documents, etc.
Then, create your own subfolder underneath that folder, and create the file inside that subfolder.

cannot create a text file in C++

I'm using an ofstream object to create and print a string to a text file, but it doesn't work. this is my code :
#include <iostream>
#include <fstream>
using namesace std;
int main()
{
ofstream output("d:\\data.txt");
output << "this is my text" << endl;
output.close();
return 0;
}
The file data.txt was created when I set output("data.txt"). The text file was created in the same folder that contains the source code. But when I set output(d:\\data.txt) or any other location, it was not created at all. This code has also worked well in other computer and the problem only occurs in my laptop. I'm using visual stdio 2013 and operated by
Windows 10 pro.
Try making a file manually in d:\\, then get the complete, correct directory of the file from its properties. That way, you will know any mistakes you are making in specifying the directory of the file to be created.

Not able to read data from the file in xcode

I am a beginner c++ programmer and I was accustomed to using Visual Studio before, but i am now using mac and i use xcode now. In xcode, i am not able to read data from the file (so i am also not able to get the output.) Which setting should i change in xcode to read data from the file(the file is in the same folder as the project) properly ?
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
//in thefile.txt i only have a string "hello"
int main() {
string text; //since i only have a string in the file. So this is a variable representation for it
ifstream myfile;
myfile.open("thefile.txt");
myfile >> text; //extract the word from the file
cout << "The following is the data in the file: " << text <<endl; //trying to print The following is the data in the file: hello
return 0;
}
//Output is "The following is the data in the file: "
Probably the most straightforward way is to use a fully qualified file name to take the guesswork out of it. If you're not sure of the full name, you can open up a window in the OS X Terminal program, type "file ", and then drag your file from a Finder window onto that command line. Terminal will fill in the full path. "file" is an innocuous command that will tell you information about your file type. But the important thing is, you will have a full path that you can then copy from Terminal and paste into your code.
If your file path has blanks in it, you may have to manually remove the backslash characters that will appear.
Xcode doesn't have a setting per se (that I know of) to determine what directory is active when you launch your program. But a full path takes the guesswork out of it.

unable to open file stream c++

I am working with Xcode and I am having trouble opening a file stream to assign variables from a text file. I speculate that placing the txt file in the same directory as the project would allow me open the stream without including the entire dir. I have been messing with this for a little while to no avail can I get it to work properly. I believe I was able to read data at one point, but I think the string printed was in unicode (not sure). It is a very simple program.. I would think that it would work.
I think my problem has to do with the directory the example is in and how Xcode works with project files. I just put the example file in the project folder and hoped that it would work.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
string name;
ifstream infile;
infile.open("example.txt");
if(infile.is_open())
{
infile >> name;
}
else
cout << "Unable to open file";
cout << name;
return 0;
}
First of all, remember, that working directory is not always the same directory where the program's binary resides.
Change:
infile.open("example.txt");
to:
infile.open("/full/path/to/program/directory/example.txt");
where /full/path/to/program/directory/ is the location of folder, where program (and thus example.txt file) is placed. It should fix the issue.
By the way, you may also want to read this question, that addresses very similar problem.
Also, read about getcwd() function.

ifstream not opening file

In this function i am trying to open a file that contains a set of characters that i want to assign to my matrix array, however whenever i run this program the console displays an error that says that the file is not open. Another question, if i add that file to my resource folder how do i specify to access that file and not the one that i have in the root of my hard drive?
ifstream readSecondMap("C:\\map_2.txt", ifstream::in);
void Stage::populateStage(ifstream &myStage, char (&myArray)[mapXcor][mapYcor]) {
if(myStage.is_open()){
for(int a = 0; a < mapXcor+1; ++a){
for(int b = 0; b < mapYcor+1; ++b){
myArray[a][b] = (char) myStage.get();
}
}
myStage.close();
} else {
std::cout << "Error: Unable to open File" <<std::endl;
}
}
The issue is most likely one of the following:
1) map_2.txt does not exist in the location you specified in your ifstream declaration.
2) You do not have sufficient rights to access the root folder of your C drive.
I advise moving the file to the same folder that your code is stored in temporarily and trying to get it to work with that location first to verify that the issue is with file location or access rights rather than something you're doing in your code. Then move it to your resource folder, and use a relative path name to access it if it works. If it doesn't work when the file is in the same folder as your code and when you have the pathname written correctly, then you are probably doing something wrong in your code and would need to post a larger portion of the code to expose the issue to us.
Just as #TianyunLing noted:
I've tested on KUbuntu 12.10:
Open error: if map_2.txt does not exist, the error will occur.
File path:
folder1
+------- file1
+------- file2
folder2
+------- program
+------- file3
for your program to visit file1, use "../folder1/file1", to visit "file3", use file3. (suppose that you don't change your program working directory)
One more thing, you don't need to specify ifstream::in for ifstream.