Enter File Name When Executing Program In C++ - c++

I'm learning C++, then i was searching for some codes for learn something in the area that i love: File I/O, but i want to know how i can tweak my code for the user type the file that he wants to see, like in wget, but with my program like this:
C:\> FileSize test.txt
The code of my program is here:
// obtaining file size
#include <iostream>
#include <fstream>
using namespace std;
int main () {
long begin,end;
ifstream myfile ("example.txt");
begin = myfile.tellg();
myfile.seekg (0, ios::end);
end = myfile.tellg();
myfile.close();
cout << "size is: " << (end-begin) << " bytes.\n";
return 0;
}
Thanks!

In the example below argv contains command line arguments as null terminated string array and argc contains an integer telling you how many arguments where passed.
#include <iostream>
#include <fstream>
using namespace std;
int main ( int argc, char** argv )
{
long begin,end;
if( argc < 2 )
{
cout << "No file was passed. Usage: myprog.exe filetotest.txt";
return 1;
}
ifstream myfile ( argv[1] );
begin = myfile.tellg();
myfile.seekg (0, ios::end);
end = myfile.tellg();
myfile.close();
cout << "size is: " << (end-begin) << " bytes.\n";
return 0;
}

main() takes parameters:
int main(int argc, char** argv) {
...
ifstream myfile (argv[1]);
...
}
You could also get clever, and loop for each file specified on the command line:
int main(int argc, char** argv) {
for (int file = 1; file < argc; file++) {
...
ifstream myfile (argv[file]);
...
}
}
Note that argv[0] is a string pointing to the name of your own program.

Main takes two arguments, which you can use to do this. See this:
Uni ref
MSDN reference (has VC specific commands

Related

Passing a file into a function

I'm trying to create a program that passes a file to a function. The function is supposed to detect how many lines are in my file. I don't think I'm passing the file correctly into my function, I've tried several different ways. Any help will be greatly appreciated.
#include <iostream>
#include <fstream>
#define die(errmsg) {cerr << errmsg << endl; exit(1);}
using namespace std;
int num_of_lines(ifstream file)
{
int cnt3;
string str;
while(getline(file, str))cnt3++;
return(cnt3);
}
int main(int argc, char **argv)
{
int num_of_lines(ifstream file);
string file;
file = argv[1];
if(argc == 1)die("usage: mywc your_file"); //for some reason not working
ifstream ifs;
ifs.open(file);
if(ifs.is_open())
{
int a;
cout << "File was opened\n";
a = num_of_lines(file);
cout <<"Lines: " << a << endl;
}
else
{
cerr <<"Could not open: " << file << endl;
exit(1);
}
ifs.close();
return(0);
}
Two problems with the function. First, you should pass the stream by reference. Second, you just forgot to initialise your counter.
int num_of_lines( ifstream &file )
{
int cnt3 = 0;
string str;
while( getline(file, str) ) cnt3++;
return cnt3;
}
The other thing is you're passing file to it (which is a string) instead of ifs. Change the call to:
a = num_of_lines( ifs );

How do I print the content of a file?

How can I print the contents of a file, the name of which is specified via my program's command line?
I do not know how to give the name of file by command line and how to work with it.
For ex this is does not work:
int main(int argc, char *argv[])
{
FILE *f;
char s[20];
cin >> s;
f=fopen_s(s,"rt");
std::cout << f;
_getch();
return 0;
}
error C2660
#include <iostream>
#include <fstream>
int main(int argc , char *argv[])
{
if(argc < 2)
{
std::cout << " Wrong usage " << std::endl;
exit(0);
}
std::string file_name = argv[1];
std::ifstream fs;
fs.open(file_name.c_str());
std::cout << file_name << std::endl;
std::string line ;
while(fs >> line)
{
std::cout << line << std::endl;
}
return 0;
}
You cannot use << operator with char[]
Solution : You can use std::string
std::string s;
Use the string's c_str() value as name in fopen_s(name, "rt")
Solution : You need to put the file in the same directory as the executable
f = fopen_s(s.c_str(), "rt");
You cannot cout << FILE *f
Solution : read file content line by line as you print each line
char* line; //used to receive data for each line
int length; //used to represent how many characters have received
while ((getline(&line, &length, f) != -1) {
print("%s", line);
}

how to read command output line by line in gcc in windows just as with the standard input?

This is what I tried:
#include <iostream>
#include <string>
int main(int argc, char const *argv[]) {
using namespace std;
for (string cin_line; getline(cin, cin_line);) {
cout << cin_line << endl;
}
FILE* pipe = popen("app.exe", "r");
for (string result_line; getline(pipe, result_line);) {
cout << result_line << endl;
}
pclose(pipe);
return 0;
}
It doesn't compile, the result is:
no matching function for call to 'getline(FILE*&, std::__cxx11::string&)'
Second example I've found here: https://stackoverflow.com/a/10702464/393087
But it seems mingw doesn't have pstream included: fatal error: pstream.h: No such file or directory - edit: ok I know, I missed that this is not a GCC library, it is named like it was but this is separate download: http://pstreams.sourceforge.net/
I know how to do it using buffer and get whole output on single line (like here: https://stackoverflow.com/a/478960/393087 ) then explode the line by \n and get my array, but the point here is that I must provide the output as soon as the input comes in.
Also I tried example from here: https://stackoverflow.com/a/313382/393087 - I've added main function to that:
#include <cstdio>
#include <iostream>
#include <string>
int main(int argc, char const *argv[]) {
using namespace std;
FILE * fp ;
if((fp= popen("/bin/df","r")) == NULL) {
// error processing and exit
}
ifstream ins(fileno(fp)); // ifstream ctor using a file descriptor
string s;
while (! ins.eof()){
getline(ins,s);
// do something
}
return 0;
}
This also doesn't compile:
error: variable 'std::ifstream ins' has initializer but incomplete type
ifstream ins(fileno(fp)); // ifstream ctor using a file descriptor
You can't do this:
FILE* pipe = popen("app.exe", "r");
for (string result_line; getline(pipe, result_line);) {
cout << result_line << endl;
}
pclose(pipe);
You need to do this:
#include <boost/noncopyable.hpp>
#include <boost/iostreams/stream.hpp>
#include <boost/iostreams/device/file_descriptor.hpp>
FILE* pipe = popen("app.exe", "r");
boost::iostreams::file_descriptor_source
source(fileno(pipe), boost::iostreams::never_close_handle);
boost::iostreams::stream<boost::iostreams::file_descriptor_source>
stream(source, 0x1000, 0x1000);
string result_line;
while (getline(stream, result_line)) {
cout << result_line << endl;
}
:)

C++ command line args (file) not found?

I have the following main method:
int main(string argf)
{
ifstream exprFile(argf);
string inExpr;
if (exprFile.is_open())
{
while ( getline(exprFile,inExpr) )
{
//do stuff
}
exprFile.close();
}
else cout << "Unable to open file";
system("pause"); // to wait for user input; allows the user to see what was printed before the window closes
return 0;
}
I have run this program from the command line using the following:
"C:\Complete Filepath\Project2.exe" "C:\Differnt Filepath\args.txt"
C:\Complete Filepath\Project2.exe C:\Differnt Filepath\args.txt
"C:\Complete Filepath\Project2.exe" "args.txt"
C:\Complete Filepath\Project2.exe args.txt
The last two with args.txt being in the same directory as the executable. All four gave the "Unable to open file" result. Attemping to print the argf value before doing anything with it yielded nothing at all. A completely blank print statement.
I then went into the Visual Studio 2010 options and added all variations of the args.txt file under the arguments section there with the file in different locations as well and nothing works.
What am I doing wrong?
How are you supposed to open a file passed as an argument on the command line?
int main ( int argc, char *argv[] )
This is correct way to get argument from main.
argc is number of arguments. argv is argument list.
Actual argument will start with index = 1. Value at index 0 will be always program name.
In your example,
"C:\Complete Filepath\Project2.exe" "C:\Differnt Filepath\args.txt"
argc = 2
argv[0] = "Project2.exe"
argv[1] = "C:\Differnt Filepath\args.txt"
Yay, code!
#include <iostream>
#include <fstream>
using namespace std;
int main(int argc, char* argv[])
{
ifstream exprFile;
string inExpr;
for( int i = 1; i < argc; i++) { // 0 is the program name
exprFile.open(argv[i]);
if (exprFile.is_open()) {
while ( getline(exprFile,inExpr) ) {
cout << "Doing stuff on line: " << inExpr << "\n";
}
exprFile.close();
}
else cout << "Unable to open file " << argv[i];
}
}

C++ fstream multiple input files

I am writing a simple program to take in two files. The terminal command line looks like this.
./fileIO foo.code foo.encode
When it runs, the second file is not read in. When I enter
./fileIO foo.code foo.code
it works. I can't seem to figure out why the second one is not opening. Any ideas? Thanks!
#include <fstream>
#include <iostream>
#include <queue>
#include <iomanip>
#include <map>
#include <string>
#include <cassert>
using namespace std;
int main( int argc, char *argv[] )
{
// convert the C-style command line parameter to a C++-style string,
// so that we can do concatenation on it
assert( argc == 3 );
const string code = argv[1];
const string encode = argv[2];
string firstTextFile = code;
string secondTextFile = encode;
//manipulate the first infile
ifstream firstFile( firstTextFile.c_str(), ios::in );
if( !firstFile )
{
cerr << "Cannot open text file for input" << endl;
return 1;
}
string lineIn;
string codeSubstring;
string hexSubstring;
while( getline( firstFile, lineIn ) )
{
hexSubstring = lineIn.substr(0, 2);
codeSubstring = lineIn.substr(4, lineIn.length() );
cout << hexSubstring << ", " << codeSubstring << endl;
}
//manipulate the second infile
ifstream secondFile( secondTextFile.c_str(), ios::in );
if( !secondFile )
{
cerr << "Cannot open text file for input" << endl;
return 1;
}
char characterIn;
while( secondFile.get( characterIn ) )
{
cout << characterIn << endl;
}
return 0;
}
One thing you might want to try is adding the close() call as is standard procedure after you're done using files. Sometimes issues arise with re-opening files if they were not closed properly in a previous run.
firstFile.close();
secondFile.close();
Also, you may try restarting the computer if there is some lingering file handle that hasn't been released.