Saving A File to Directory C++ - c++

So i've spent about 30minutes on this with no luck. Tried many ways of saving the file. It works when i save it into:
C:\Users\jsmit\OneDrive\Documents\Visual Studio 2017\Projects\Password Generator\Password Generator
but not when i try and save it into:
C:\Users\jsmit\OneDrive\Documents
or:
C:\Users\jsmit\Documents\New folder
This is my code for saving a file:
void savePassword(string stringpassword, string site) {
ofstream out("C:\Documents\New folder\output.txt", ofstream::app); // DOESN'T WORK
out << site << ": " << stringpassword << endl; // This is where it saves the password into the text file
out.close(); // Closes file
}
If i put:
ofstream out("Password.txt", ofstream::app); // ofstream:app stops overwrite
it works.
EDIT:::: Allows me to save to H:\New folder but not C: drive? How to fix?
How do i make it so it saves it into: C:\Users\jsmit\OneDrive\Documents

The problem is the character \ use \\ or /
See here for more details:
In C, all escape sequences consist of two or more characters, the
first of which is the backslash, \; the remaining characters determine
the interpretation of the escape sequence. For example, \n is an
escape sequence that denotes a newline character. The remainder of
this article focuses on C; other programming languages are likely to
have different syntax and semantics.

Like others said \ is the escape character. You need to use double backslashes when meaning for \ to be included.

You can't just write into C: unless you are admin.
Use the shortcut for the Home Folder "%USERPROFILE%" to access this folder, then you can use "%USERPROFILE%\OneDrive\Documents"
Also, make sure the folder exists before writing any file into it. The folder won't be automatically created, you have to make it yourself.
Also, take a look at other answers, '\' character should be '\\'

Related

c++ Write Chars into Batch file

Why does this give error at '%' as incorrect formatted speical character.
ofstream batch;
batch.open("C:\tesfile.bat", ios::out);
batch << "#echo off\n";
batch << "set Dir=C:\Users\%USERNAME%\AppData\ \n";
Also i gave c:\ to create bat file it creates bat file at the app folder (where the app is placed).
Please help.
You should either escape special character \ in your string, or use C++11 raw literals (much better option in my view!) like this:
batch.open(R"(C:\tesfile.bat)", ios::out);
In a string, you need to escape your backslashes (\) as \\. Otherwise, the compiler thinks you are trying to insert special characters like \n:
batch.open("C:\\tesfile.bat", ios::out);
batch << "#echo off\n";
batch << "set Dir=C:\\Users\\%USERNAME%\\AppData\\ \n";
As a thought exercise, imagine what would happen if you didn't escape your backslashes:
batch.open("C:\nifty_folder", ios::out); //\n in "nifty" causes a newline!
In fact, your original code has an unintended consequence!
batch.open("C:\tesfile.bat", ios::out); //\t is a tab!

C++- Code not working to alternate lines when writing on a text file

I need to create a program that reads strings from two different files and write these strings on a new file. The thing is, it must alternate both files, meaning that it should write a line from one file, and then one line from the other, and so on.
I'm having a problem with my code, it writes the first line of the first file, and then it writes all lines from the second file.
Anyone knows how to solve this problem?
do {
getline(archivo1, sLinea);
archivoS << sLinea << endl;
getline(archivo2, sLinea2);
archivoS << sLinea2 << endl;
} while (!archivo1.eof() && !archivo2.eof());
The code looks correct and should work under normal circumstances. This might be a problem with the encoding of the second file, where the newline characters are not being recognised as such on your platform, which could result in the entire second file being interpreted as a single line by the C++ standard library.
Windows (CR+LF), Unix/Linux (LF), and Mac (CR) each have different conventions for newlines. Search about the carriage return and line feed characters across platforms to learn more about this topic.
To identify if this is the issue, try running the code on two separate copies of the first file to see if it produces the expected output?
If newline encoding is your issue, you will either need to convert the second file to use your platform's newline encoding (you can use a tool like Notepad++ to easily do this) or incorporate logic which controls for this into your program.
Check your second file. In all likelihood it does not contain the line delimiter "\n" , per line. There may be only one at the end

Read files in C++

This is my simple code:
#include "C:\Users\Myname\Desktop\Documents\std_lib_facilities.h"
using namespace std;
//**************************************************
int main()
try {
ifstream ifs("C:\Users\Myname\Desktop\raw_temps.txt");
if(!ifs) error("can't open file raw_temps.txt");
keep_window_open("~~");
return 0;
}
//**************************************
catch(runtime_error& e) {
cerr<<e.what();
keep_window_open("~~");
return 1;
}
The .txt file is in address "C:\Users\Myname\Desktop\raw_temps.txt".
When I run that, only the error (" ... ") function operates and theifs can't open the raw_temps.txt file.
Why please?
I believe that this problem is are due to some misunderstanding your use of backslashes as a path separator. Paths in c++ should be written with normal slashes, and not backslashes to prevent errors like those you have done here. This is because a single backslash is used as an escape character, meaning that it combined with the next symbol becomes a new symbol. An example is "\n" for newline or "\t" for tab.
To prevent this, and to make the code run on all platforms, and not just those using backslash as path separator, stick to slash as a path separator.
More information on this can be found on Marshal Clines C++ FAQ
And, yes, you can make this work with double backslashes, but then you are making a bad habit IMO. Plus that it is two characters where only one is needed.
You need to ignore "\" as it is a wildcard character. Replace "\" with "\".
Change this line
ifstream ifs("C:\Users\Myname\Desktop\raw_temps.txt");
To this
ifstream ifs("C:/Users/Myname/Desktop/raw_temps.txt");
\ is used to mark escape characters, so unless you use \\, the string will not look like what you think it should. You can see this by using a debugger and breaking on this line.
best option is to keep the file you want to open in the folder of source code and write this
ifstream ifs("raw_temps.txt");

Reading in quoted CSV data without newline as endline

I have an issue with a file I am trying to read in and I don't know how to do solve it.
The file is a CSV, but there are also commas in the text of the file, so there are quotes around the commas indicating new values.
For instance:
"1","hello, ""world""","and then this" // In text " is written as ""
I would like to know how to deal quotes using a QFileStream (though I haven't seen a base solution either).
Furthermore, another problem is that I also can't read line by line as within these quotes there might be newlines.
In R, there is an option of quotes="" which solves these problems.
There must be something in C++. What is it?
You can split by quote (not just quote, but any symbol, like '\' for example) symbol in qt, just put \ before it, Example : string.split("\""); will split string by '"' symbol.
Here is a simple console app to split your file (the easiest solution is to split by "," symbols seems so far):
// opening file split.csv, in this case in the project folder
QFile file("split.csv");
file.open(QIODevice::ReadOnly);
// flushing out all of it's contents to stdout, just for testing
std::cout<<QString(file.readAll()).toStdString()<<std::endl;
// reseting file to read again
file.reset();
// reading all file to QByteArray, passing it to QString consructor,
// splitting that string by "," string and putting it to QStringList list
// where every element of a list is value from cell in csv file
QStringList list=QString(file.readAll()).split("\",\"",QString::SkipEmptyParts);
// adding back quotes, that was taken away by split
for (int i=0; i<list.size();i++){
if (i!=0) list[i].prepend("\"");
if (i!=(list.size()-1)) list[i].append("\"");
}//*/
// flushing results to stdout
foreach (QString i,list) std::cout<<i.toStdString()<<std::endl; // not using QDebug, becouse it will add more quotes to output, which is already confusing enough
where split.csv contains "1","hello, ""world""","and then this" and the output is:
"1"
"hello, ""world"""
"and then this"
After googling I've found some ready solution. See this article about qxt.

executing filenames with spaces in cmd pmt Passed from c++ program

I am currently working on getting my program to execute a program (such as power point) and then beside it the path to the file I want to open. My program is getting the file's path by using:
dirIter2->path()
I get the 2 paths of the program and file, Merge them as one string and pass them into the following:
system(PathTotal.c_str())
this is working great but my only issue is that when the file name has a space in its name command prompt says it cannont find the file (becuase it thinks the file name ends when it gets to the first space. I have tried to wrap it with quotes but it is the acutal file name that need to be wrapped.
(eg. i have tried "C:\users\bob\john is cool" but it needs to be like this: C:\users\bob\"john is cool")
Does anyone have any suggestions on how I could fix this? I was thinking about getting the path to the folder to where the file and then getting the file name. I would wrap the file name with quotes then add it to the folder's path. I have tried using the ->path() like above but the only problem is that it only goes to outside of the folder's directory?
Is there a boost command that could get the enitre path to the file without getting the file aswell?
I am not commited to this idea if anyone has any better suggestions
Thanks
In both C and C++, the '\' is an escape character. For certain things (like '\n' or '\t') it inserts a control code; otherwise, it just gives you the next character.
So if you do something like:
fopen("C:\users\bob\john is cool", "r");
it's going to try to open a file named
C:usersbobjohn is cool
If you want those '\' characters in the output, you have to escape them. So you'd want:
fopen("C:\\users\\bob\\john is cool", "r");
On Windows with Visual Studio, I've also successfully used Unix-style separators:
fopen("C:/users/bob/john is cool", "r");
And in fact, you can mix them up:
fopen("C:/users\\bob/john is cool", "r");
I'm not familiar with C string operations, but couldn't you do the following rather easily?
int i = path.lastIndexOf("\\"); //Find the index of the last "\"
String quotedPath = path.substring(0, i+1); //Get the path up until the last "\"
quotedPath += "\"" + path.substring(i+2) + "\""; //Add quotes and concatenate the filename
Sorry for the Java, its the closest thing that I'm familiar with. I've made this a community wiki in case someone can edit the code to the equivalent C.
I'd also like to add that sometimes it is necessary to escape spaces as in the following:
cmd.exe -C C:/Program\ Files/Application\ Folder/Executable\ with\ spaces.exe
or
cmd.exe -C C:\\Program\ Files\\Application\ Folder\\Executable\ with\ spaces.exe