How to read many sets of data from a file - c++

I have to read the four data elements viz student name, father's name, roll no and age from a file.
I am using inps as input file stream and outs as output data stream. I have 10 data sets in my input file. But this program writing only 1st data set in output file and ignoring rest 9 sets. Please give some suggestions to this problem.
string line;
int data;
while (inps) {
getline(inps,line); //read from file and put in line
s1.setName(line);
getline(inps,line);
s1.setFatherName(line);
inps>>data;
s1.setRollNo(data);
inps>>data;
s1.setAge(data);
outs.open("output",ios::app);
outs<<"Student name: "<<s1.getName()<<endl<<"Father’s name: "
<<s1.getFatherName()<<endl;
outs<<"Roll number: "<<s1.getRollNo()<<endl<<"Age: "
<<s1.getAge()<<endl<<endl;
outs<<"============================================================="
<<endl<<endl;
}
inps.close();
//write in output file
outs.close();

Don't continually re-open the same ofstream:
at all, it's just silly
certainly not without closing it properly first

Another problem in this program is that while entering in the loop, it checks inps==0 or not and still its uninitialized!
So, instead of while(inps), we have to write for(getline(inps,line);line!="";getline(inps,line))
and then remove very first line of code and it all works nicely.

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);

C++ open() not working for any apparent reason

ifstream infile;
infile.open("BONUS.txt");
string info;
if (!infile)
cout << "File Open Failure" << endl;
else
{
while (infile >> info)
cout << info << endl;
infile.close();
}
This is my code. And no matter what I do, my file always fails to open. It enters the if and exits. What could possibly be the problem? My text file is saved in the correct directory and nothing seems to be wrong with it.
There are two parameters in open(), file to be opened and mode. The mode refers to what you can do with that file, i.e. write to, read from, etc.
There are six possible modes when using open():
Parameter in stands for input. The internal stream buffer enables input. (Use for reading the file.)
Parameter out stands for output. The same internal buffer enables output. (Use for writing to the file.)
Parameter binary allows all operations to be done in binary, instead of text.
Parameter ate stands for at end and begins output at the end of the file.
Parameter app stands for append and output events happen at the end of the file.
Parameter trunc stands for truncate. All contents in existence before it is opened are deleted.
It seems that you want to write to the file, in which case use out.
ifstream infile;
infile.open("BONUS.txt", out);
If you are not using the correct mode, the function will fail. If you have any more questions, Google fstream::open().

Deleting a specific line in a txt file using istream/ofstream in c++

Here is the code I'm having a trouble with, I have a .txt file that contains a list of users and their passwords using this format: user;password.
I need to search for a user in the file and then delete the line which contains this user.
void deleteauser()
{
string user;
cout<<"Which user do you wish to delete?";
cin>>user;
string line;
string delimiter=";";
string token,token1;
ifstream infile;
infile.open("users.txt",ios::in);
while (getline(infile,line,'\n'))
{
token = line.substr(0, line.find(delimiter));
token1=line.substr(token.length(), line.find('\n'));
if(token==user)
{
//here i need to delete the line of the user that has been found
}
}
infile.close();
}
Read the input file, line by line, writing to a temporary file. When you find lines you don't want then just don't write them to the temporary file. When done rename the temporary file as the real file.
To edit a file you have 2 options:
Read in every line and write out those you want to keep
Seek to the part of the file you want deleted and replace the text with spaces (or similar)
You have the first half pretty much done - just write out what you read to a temporary file and delete/rename to make it the original.
For the second option, you can write to the input file at that point if you use an iofstream (be aware of buffering issues). The better option is to use seekp or seekg to get to the right point before overwriting the file.

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