How to handle Unix pipe - c++

How do I get the filename from redirection from the shell in my C++ code? i.e. ./MyProgram < myfile , I want to get myfile as the filename and its content line by line.
**Edit: I managed to get the input from file. Thanks for the help. However, after the looping through the file content, I want to keep user input with cin. It's like this:
while (true)
{
if (cin.eof() == false)
{
getline(cin, line);
cout << line;
}else{
cin >> choice;
}
}

You can't (at least not portably). This information is not provided to the program. Instead, you can access the data from myfile (in your example) by reading from standard input. E.g., you can use C++'s getline with cin as the first parameter.

Depending on the shell, you may have inherited a descriptor representing an actual file or a pipe. If it's an actual pipe (i.e. fifo), the name won't mean much. But you can get the name on linux (and on Windows, but it doesn't sound like you're interested in that).
See Getting Filename from file descriptor in C

Related

How to determine I've reached EOF with a non coded file?

I've looked up several instances in EOF, but in all instances EOF is being used on a file that is part of the program, for example:
std::fstream myFile("file.txt", std::ios::in);
while(!myFile.eof()) {
/*program*/
}
However in this instance, I'm not using a file as part of the code. I'm just using basic cin commands. There's a command to quit, but let's say a user runs the program like this:
./program <myFile.txt> myOutput
Let's say that myFile had these commands in this:
add 1
add 2
delete 1
print
That's all fine, but they forgot to add a quit command at the end, so the code won't stop. So how do I get the code to detect EOF in this situation and stop?
The correct way to detect end-of-file is to check each input operation for success.
For example, with getline you'd use
std::string line;
while (std::getline(std::cin, line)) {
// do stuff with line
}
Or with >>:
while (std::cin >> x) {
// do stuff with x
}
This applies to all input streams, whether they're from files (fstream) or e.g. cin.
End of file (EOF) means there is nothing more to read from the file buffer, it’s not something one puts explicitly at the file itself.. you should still get there fine with your code
Another way is to read the buffer until there are no more bytes to read there

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().

C++ windows system ("path") not working if there is space somewhere

My path to the executable file is:
C:\Users\FirstName LastName\Desktop\Saturated.exe
My program is:
while (s != "Exit")
{
cin >> s;
system (s.c_str());
}
Where s is string.
I tried to write:
C:\\Users\\FirstName LastName\\Desktop\\Saturated.exe
\"C:\\Users\\FirstName LastName\\Desktop\\Saturated.exe\"
C:/Users/FirstName LastName/Desktop/Saturated.exe
But none of this worked because of space between FirstName and LastName. What should I do?
If you used the command line arguments to input the string, your OS would parse it correctly. If you want to input the path while running the program, your best chance is to go with std::getline, you'll read the whole line no matter what, no need for ".
Or, if you want to implement that same parsing behavior, you'll check if the first character is " (with cin.peek()), if that's the case, you'll cin.ignore() and std::getline until another ", otherwise you'll just cin >> s;.

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

Why doesn't std::getline block?

I have this code in an Objective-C class (in an Objective-C++ file):
+(NSString *)readString
{
string res;
std::getline(cin, res);
return [NSString stringWithCString:res.c_str() encoding:NSASCIIStringEncoding];
}
When I run it, I get a zero-length string, Every time. Never given the chance to type at the command line. Nothing. When I copy this code verbatim into main(), it works. I have ARC on under Build Settings. I have no clue what it going on. OSX 10.7.4, Xcode 4.3.2.
It is a console application.
It means there is input waiting to be read on the input. You can empty the input:
cin.ignore(std::numeric_limits<std::streamsize>::max();
std::getline(cin, res);
If this is happening it means you did not read all the data off the input stream in a previous read. The above code will trash any user input before trying to read more.
This probably means that you are mixing operator>> with std::getline() for reading user input. You should probably pick one technique and use that (std::getline()) throughout your application ( you can mix them you just have to be more careful and remove the '\n' after using operator>> to make sure any subsequent std::getline() is not confused..
If you want to read a number read the line then parse the number out of the line:
std::getline(cin, line);
std::stringstream linestream(line);
linestream >> value;
You can simply do:
cin.ignore();
or use
cin.clear();
cin.sync();
before using getline()