How to have a text file created based on user input C++ - c++

I'm fairly new to C++. I'm creating a code that will input a file and output the results in an output file, and using stacks and junk.
But what i want to do is create a file based on a user input. Asking the user (when a file doesn't exist in a specific directory) if they would like to create that empty file. I've done this on C# using Directory and Dictionary, but C++ isn't really clicking for me. Here's the snippet of my code (I'm not going to paste 200+ lines for one thing) and where i want to do. Ignore the comments. It's just to keep track of what I'm doing.
if (file.is_open()) //if the file is open (and works)
{
string output;
cout << "Please enter the full directory of the file you would like to have the results in" << endl;
cin >> output;
output.c_str();
file_result.open(output); //open the results file for checking answers
while (file_result.fail())
{
cout << "This file does not exist. Would you like to make one?" << endl;
}
As you see, where I ask the user if they would like to make that file is where i would want this to be.
Any help would be lovely! Transitioning from C# to C++ was a bad idea.

You can open a file for writting (in append mode) in this way:
std::ofstream ofs;
ofs.open (output.c_str(), std::ofstream::out | std::ofstream::app);
ofs << " more lorem ipsum";
ofs.close();
More information about file operations can be found here:
http://www.cplusplus.com/reference/fstream/ofstream/open/

The most basic way to create a file based off of user input is this, You should how ever include checks to make sure the path is valid and that no file exists etc.. I only have time to show you how to do this.
#include <fstream>
#include <iostream>
#include <string>
using namespace std;
int main()
{
ofstream outFile;
string path;
cout << "Please enter the full path for your file: ";
getline(cin, path);
outFile.open(path);
return 0;
}
What's happening here is quite simple the user inputs the full path (C:\Hello.txt) it's read by getline(cin, path) and is stored in path.
outfile then creates that file.
Please make sure you add checks to validate no file with that name already exists etc.. I'll update this later with a better example but this will create a file for you

Related

Adding a new line to existing txt file in c++

As a tutorial I've been a question to add new line to an existing file with a list of items. i've tried numerous ways to add it. no luck yet
ofstream outdata;
ifstream indata;
indata.open("fruits.txt");
outdata.open("fruits.txt");
if(indata.is_open()){
std::string fruit;
std::cout << "enter a fruit to list "<<endl;
std::cin >> fruit;
outdata << "\n" << fruit << "\n" << endl;
indata.close();
outdata.close();
return 0;
}
This part of the code is supposed to ask the user to enter a value. Its supposed to be stored as new line without deleting the existing line. But here I'm. I've seen a few answers here. but can't find anything understandable.
When you open a file for writing its contents are immediately removed, if the file already exists.
outdata.open("fruits.txt");
You opened the same file for writing here. This is before your code tries to read anything from the same file (I don't actually see anything in your code that tries to read it, I presume you left that part out). And by the time you get to the file it's already empty and there's nothing to read any more from it.
You have three choices:
Read the entire contents of the file into your program, and only then open it for writing and write out the new contents.
Open a different file for writing. After finishing reading and writing both files, and closing them, rename the new file to the original file.
Open the file for appending:
outdata.open("fruits.txt", std::ios::app);
It's not necessary to open it for reading, this will add to the end of the file, instead of overwriting it.

How can i solve an issue in writing data in specific file in my clr project?

I am trying to add some data to a specific file in my project. I am doing that in the function below.
void Files::write_employee(employee employeeObject)
{
fstream infile;
infile.open("employeeFile.txt",ios::in|ios::out|ios::app);
string record;
char delimiter='#';
record=employeeObject.get_id()+delimiter;
record+=employeeObject.get_name()+delimiter;
record+=employeeObject.get_password()+delimiter;
record+=employeeObject.get_age()+delimiter;
record+=employeeObject.get_gender()+delimiter;
record+=employeeObject.get_MaritalStatus()+delimiter;
record+=employeeObject.get_ministryName()+delimiter;
record+=employeeObject.get_departmentName()+delimiter;
record+=employeeObject.get_salary()+delimiter;
record+=employeeObject.get_photoPath()+delimiter;
record+=employeeObject.get_photoFileName()+delimiter;
if (infile.fail())exit(1);
else {infile<<record;
infile.close();}
}
This function explains how to add data to my file through save the entered data
in an object and save this values in string record and push it to the file.
The big problem is my file which I am trying to add data in, not created yet.
and I don't know why.
thanks in advance.
You use infile whereas you are outputting to file. While this does not affect the program code, it makes no sense and break your program readability. Use outfile instead.
Remember that it is just like cout << and cin >> for the standard I/O.
Also, try not to use ios::in when your purpose is only to output to the file and vise versa.
According to std::fstream::open example at cplusplus.com, your code is correct and the file must be created. First try to specify an absolute file path to a location that you have write access. If it does not work, print the error message using the following line of code:
cerr << "Error: " << strerror(errno);

How to make a C++ program that works with a .txt file without showing it

My program needs to use a hidden text file to keep track of user's name.
But when the program starts, if it can't find the 'Name.txt' file in the same directory, it generates one that is visible to the user.
The user can view it, edit it, and so on. How can I prevent this from happening, so that only my program can modify the file?
Also, is there a better way to keep knowledge of the name of the user (keep in mind I'm new to programming in general, not only to C++)?
#include "stdafx.h"
#include <fstream>
#include <iostream>
#include <string>
#include <Windows.h>
using std::string;
using std::cout;
using std::cin;
using std::ifstream;
using std::ofstream;
int main()
{
string line;
ifstream example;
example.open("Name.txt");
getline(example, line);
if (line.compare("") == 0)
{
example.close();
string con;
cout << "Welcome to this program!\n";
cout << "Do you want to register? (y/n) ";
cin >> con;
con[0] = tolower(con[0]);
if (con.compare("n") != 0)
{
string name;
ofstream one;
one.open("Name.txt");
cout << "What's your name? ";
cin >> name;
one << name;
one.close();
cout << "See you later " << name << ".";
Sleep(4000);
}
}
else
{
cout << "Welcome back " << line << ".";
example.close();
Sleep(4000);
}
}
EDIT : I just realised I said 'to keep track of the user'. Now I realized why you guys thought I wanted to do something bad with this program. I corrected it now, what I meant was 'to keep track of the user’s name'.
I understand that you want to maintain a file that contains the names of all the registered users, or some other kind of current-user-independent data.
The problem
Your code tries to open the file in the current working directory of the program. Unfortunately, it depends on the way the user has launched your program.
It also ignores possible errors during the opening when reading the file. So if the file isn't there, your code will open the file as ofstream for writing (which will create the file if it doesn't exist).
How to solve it ?
To fulfill your requirements, you should open the file in a predetermined location (for example fixed during the installation process, or in the program's configuration). See this article, on where to ideally store data and configuration files on windows platform.
If you want to make sure that the program only opens the file if it already exists, you should verify the result of the open on the ifstream and issue an error message if this failed:
example.open("Name.txt");
if (!example) {
cout << "OUCH ! Fatal error: the registration file couldn't be opened !" <<endl;
exit (1);
}
How to protect the file against users ?
Note however that if your program reads and writes data from the file, the user could find it also and edit it manually. This will be difficult to prevent.
Alternatively you could consider using the windows registry, which is less trivial for the user to edit (although not impossible). The major inconvenience of this approach is that it's system dependent and it will make the porting of your code to other platforms much more difficult.
If you want to fully protect your file, you could as suggested by Chris in the comment, encrypt the file. Encryption is complex business; Consider using a library such as openssl or a proven algorithm.
This will protect you against ordinary users. But you'd still be exposed to hackers able to reverse engineer your code and to find the encryption key that must be somehow embedded in your code to decrypt the file.

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.

how to make input prompt for 7 column by ifstream

I typed in a file name which I want to show on prompt screen but it says that
"'c:\test\sp.csv' is not recognized as an internal or external command,"
even though the file is available on the path.
1 - Why did this error happen? How to fix it?
C:\Users\MS>c:\test\sp.csv
'c:\test\sp.csv' is not recognized as an internal or external command,
operable program or batch file.
2 - The code below only shows one column, if I want to input for 7 columns, how would I edit the code below?
How to print out on prompt screen using ifstream for 7 column with header and price.
Date Open High Low Close Volume Adj Close
6/21/2013 1588.62 1599.19 1577.7 1592.43 5797280000 1592.43
6/20/2013 1624.62 1624.62 1584.32 1588.19 4858850000 1588.19
int main(){
int open;
string fileName;
cout <<"Enter a file name: ";
getline(cin, fileName); //c:\\test\\sp.csv
ifstream inFile(fileName.c_str(), ios::in);
while(!inFile.eof()){
inFile >> open;
cout << open << endl;
}
inFile.close();
system("PAUSE");
return 0;
}
Thank you Kelly
Looks like you're on Windows OS
.csv file extension is not an executable one. It won't get "executed", even if its present in current working directory/folder.
Probably what you want is a .exe, .com or .bat file.
Here, in this case I think you want your .CPP 's executable with command line argument.
May be something like
C:\Users\MS>c:\test\sp.exe c:\test\sp.csv' Considering your C++ file name is sp.cpp
2 . Looks like you want to display out all contents of sp.scv
You may want to read the header first (i.e the Titles), and then read the values.
There are lot of question already asked on StackOverflow, related to this, please refer them.
Also for proper formatting you may want to use std::setw