Take file as an input from the command line c++ - c++

Currently I have code that uses cin to get the name of the file to be used as input when the program is executed. I would like to have it so that when i run the program i can add the file redirection and the filename and run it as such: ./a.out < file.txt. How can i feed my file into my code using redirection.
this is an example of how i am currently taking input:
int main(){
std::string filename;
std::cin >> filename;
std::ifstream f(filename.c_str());
}

Do it like this
#include <iostream>
#include <fstream>
#include <string>
int main()
{
std::string line;
std::cout << "received " << std::endl;
while(std::getline(std::cin, line))
{
std::cout << line << std::endl;
}
std::cout << "on stdin" << std::endl;
}
You do not need to open the file yourself as the file content is passed to you on stdin as a result of using < on the command line.
This code has a drawback that if you do not input anything on stdin it freezes. Detecting that stdin is empty can only be achieved in a non portable manner (see here).
It would be better to accept your filename as a normal command line argument and open it inside your program.

Related

Visual Studio 2022 - How to save console output in .txt file and still see it in the console (i.e without redirection)

hopefully nothing too complicated :)
When I debug my application in VS 2022, I would like all the std::cout that is in the console to be saved to a .txt file, but also still show in the console itself. I added > output.txt to the command line arguments, but realized that means nothing will show in the console :/
i think u can u swich case in a do-while loop
1 is input, which u can choose to save in text file
2 is output, which read your text file
Or you can just do like this
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main()
{
string s;
cout << "Enter something: ";
getline(cin, s);
fstream file;
file.open("text.txt", ios::out);
file << s;
file.close();
file.open("text.txt", ios::in);
if (file.is_open())
{
string line;
while (getline(file, line))
{
cout << line << endl;
}
}
return 0;
}
You can use OutputDebugStringA and cout at the same time.
And set Redirect all Output Window text to the Immediate Window in Tool> Option.

Open a file with C++ and output the text that is in the file

I am trying to open a file with C++ and output the text that is in the file. I cannot seem to figure out what I am doing wrong. Here is what I have so far.
#include <iostream>
#include <string>
#include <fstream>
#include <cstdlib>
using namespace std;
int main()
{
char fileName[50];
ifstream infile;
cout << "Enter the name of the file you would like to open: ";
cin.getline(fileName, 50);
infile.open(fileName);
if(!infile.is_open())
{
exit(EXIT_FAILURE);
}
char line[75];
infile >> line;
while (infile.good())
{
cout << line << " ";
infile >> line;
}
system("pause");
return 0;
}
After I input the file name and press enter the CMD prompt just closes. I know that the file exist, but I cannot figure out why it is exiting. Obviously it is because of the exit command, but it should be open. What am I doing wrong?
You don't need to read/write the file line by line; C++ already supports to copy the file in one step. You also should use string instead of char[] for your strings; on one hand it means that you don't need to restrict the maximal length of your strings to some arbitrary length (what if your file's pathname has more than 50 characters, or the file has lines with more than 75 characters?
Note also that your file copying code is erroneous: It will remove all whitespace from the file, as infile >> line does not read a line (use readline for that), but a word, discarding whitespace.
Also, your code should give an error message if it couldn't open the file, instead of just silently returning (you do provide an error return, which is very good, but unless you call it from something that actually gives you feedback on the error return, you'll never learn about it.
Finally, the system("pause") should probably be done in an RAII class, so it is guaranteed to be exited on return (however, exit will not call destructors, so unless you want to use atexit, you should use return in `main`` instead). A better idea would, however, be to not put this into the code, but instead run it in a terminal that doesn't immediately close after the program finishes.
Here's a program that implements those suggestions:
#include <iostream>
#include <fstream>
#include <cstdlib>
int main()
{
// make sure that system("pause") is called on all exit paths
struct cleanup
{
~cleanup() { std::system("pause"); }
} do_cleanup;
// get the file name
std::string filename;
std::cout << "Enter the name of the file you would like to open: ";
std::getline(std::cin,filename);
if (!std::cin)
{
std::cerr << "Failed to read the file name.\n";
return EXIT_FAILURE;
}
// open the file
std::ifstream infile(filename.c_str());
if (!infile)
{
std::cerr << "Could not open file: " << filename << "\n";
return EXIT_FAILURE;
}
// print the file
std::cout << infile.rdbuf();
// close the file
infile.close();
if (!infile)
{
std::cerr << "Could not properly close file: " << filename << "\n";
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
There is no need to use a char[]. You've even #included string so just use that.
string fileName;
cout << "Enter the name of the file you would like to open: ";
cin >> fileName;
// or
// getline(cin, fileName);
ifstream infile(fileName);
if (infile.fail()) {
exit(EXIT_FAILURE);
}
string line;
while (infile >> line) {
cout << line << " ";
}
system("pause");
return 0;
I also modified a few things to make it a bit cleaner.
Thanks for the help. Yes the file was in the wrong folder. It was a newb oversight!

Strange behaviour of file.get() on mac os x

some strange behaviour occurred. So, i have program, which i just copypasted from cplusplus.com.
#include <iostream> // std::cin, std::cout
#include <fstream> // std::ifstream
int main () {
char str[256];
std::cout << "Enter the name of an existing text file: ";
std::cin.get (str,256); // get c-string
std::ifstream is(str); // open file
while (is.good()) // loop while extraction from file is possible
{
char c = is.get(); // get character from file
if (is.good())
std::cout << c;
}
is.close(); // close file
return 0;
}
In the same folder, where my program is, I have file named "hello.txt", which consist of 1 line "abc abc".
So, after I run program and input "hello.txt", I have following line:
hsdhs131313dhhsd
Which is, of course, not the content of "hello.txt". I am using mac os x and clang for compilation. Where is the problem, why code sample from official site not working? Thank you in advance

Simple File-I/O Program C++

#include <iostream>
#include <fstream>
#include <stdlib.h>
#include <process.h>
using namespace std;
int main(){
system("cls");
char mline[75];
int lc=0;
ofstream fout("out.txt",ios::out);
ifstream fin("data.txt",ios::in);
if(!fin){
cerr<<"Failed to open file !";
exit(1);
}
while(1){
fin.getline(mline,75,'.');
if(fin.eof()){break;}
lc++;
fout<<lc<<". "<<mline<<"\n";
}
fin.close();
fout.close();
cout<<"Output "<<lc<<" records"<<endl;
return 0;
}
The above code is supposed to read from the file "data.txt" the following text
"The default behaviour of ifstream type stream (upon opening files ) allows users
to read contents from the file. if the file mode is ios::in only then reading is
performed on a text file and if the file mode also includes ios::binary along with
ios::in then, reading is performed in binary mode. No transformation of characters
takes place in binary mode whereas specific transformations take place in text mode."
and create a file out.txt , in which the same text is stored using line numbers ( A line can have 75 characters or ends at '.' - whichever occurs earlier ).
Whenever I run the program, it just gets stuck at the console - which doesnt respond upon pressing any keys whatsoever.
Can someone tell me what's going on in here ?
If any one of the attempted reads in the file is longer than 74 characters, getline will set the failbit for fin, and you will never reach the end of the file. Change your code to the following:
for (; fin; ++lc) {
fin.getline(mline,75,'.');
if (!fin.eof() && !fin.bad())
fin.clear();
fout<<lc<<". "<<mline<<"\n";
}
This will break your loop if you reach the end of the file or if something catastrophic happens to the stream. You'll also need to think about handling the extra read that is performed if the file ends with a period.
Consider switching to std::string.
#include <iostream>
#include <fstream>
#include <string>
int main()
{
int lc = 0;
std::ofstream fout("out.txt");
std::ifstream fin("data.txt");
for (std::string line; getline(fin, line, '.'); )
fout << ++lc << ". " << line << "\n";
std::cout << "Output " << lc << " records\n";
}

How to open a file that the user gives in output screen using c++

I want the user to give the file name in output screen,for the file to be opened while running the program .More specifically, if the user gives a file name in output screen, my program should open that file for him. How can i code this using files in c++? Can anyone give an example?
example code:
#include <iostream>
#include <fstream>
int main() {
std::string filename, line;
std::cout << "Input file name: ";
std::cin >> filename;
std::ifstream infile(filename);
if(!infile)
std::cerr << "No such file!" << std::endl;
else {
std::cout << "File contents: " << std::endl;
while(infile >> line)
std::cout << line << std::endl;
}
}
contents of test.txt:
hello
world
how
are
you
program output (on console):
Input file name: test.txt
File contents:
hello
world
how
are
you
the way this works is, you declare two strings - one that will be the filename and the other that will be serve as a temporary buffer for each line in file.
when the user inputs a file name, depending on whether the file exists or not, the program will either output an error, or declare and initialize a file stream infile (this basically opens a stream to your file and allows you to extract [or input] data from the desired file).
once that is done, the program will read the file line by line while(infile >> line) and output the contents of each file to console.