Sign in to follow this  
Savalric

Calling Files

Recommended Posts

Can you actually use the command-line arguements to call files?

The tutorial I'm reading is showing me code on how to use int main() but it isn't actually showing me how to open any files... I'm not sure if it's referencing files within the program or text files outside of the original source file.

This is the small bit of code he wrote with the comments:

#include <fstream>
#include <iostream>

using namespace std;

int main ( int argc, char *argv[] )
{
  if ( argc != 2 ) // argc should be 2 for correct execution
    // We print argv[0] assuming it is the program name
    cout<<"usage: "<< argv[0] <<" <filename>\n";
  else {
    // We assume argv[1] is a filename to open
    ifstream the_file ( argv[1] );
    // Always check to see if file opening succeeded
    if ( !the_file.is_open() )
      cout<<"Could not open file\n";
    else {
      char x;
      // the_file.get ( x ) returns false if the end of the file
      //  is reached or an error occurs
      while ( the_file.get ( x ) )
        cout<< x;
    }
    // the_file is closed implicitly here
  }
}

and then is the code I wrote, minus comments, plus cin.get(); so I can actually see the fruits of my labor before it closes.

#include <fstream>
#include <iostream>

using namespace std;

int main ( int argc, char *argv[] )
{
	if ( argc != 2 )
		cout<<"usage: " << argv[0] << " <filename>\n";
	else
	{
		ifstream the_file ( argv[1] );
		if ( !the_file.is_open() )
			cout<<"Could not open file\n";
		else
		{
			char x;
			while (the_file.get( x ) )
				cout<< x;
		}
	}
	cin.get();
}

Is there some concepts that I missed? Because this is the second time file opening was reference and I wasn't actually able to open a file.

 

EDIT: Oops, i still had a mistake in the code here: cing.get should've been cin.get. I had already fixed that issue before, not sure how the g got back but at any rate, the code runs the same as I mentioned.

Edited by Savalric

Share this post


Link to post
Share on other sites

The original code ran then closed without showing any information. Once I added the cin.get it just showed the address for the source file that was running the code. I'm using visual studio 2010 to just run and debug the code, as I'm actually still learning. And that's the thing, I don't know how to do that. I assume that something in this bit of code will allow me to open and read a file, but the teacher did a terrible job at explaining how to do this. In fact, he only explained the basics of each line of code and not how to use it.

Share this post


Link to post
Share on other sites

I think you are missing 2 key concepts.

1)

int main(int argc, char **argv)

This line of code is creating an entry point for your program. It recieves 2 arguments from the calling environment. The first, "argc" is a count the second "argv" is a list of strings of length 'argc'.  When you go to the commandline and run a program "dir -w -p" everything after the command is broken up into space seperated strings and given to the argc/argv of the program. So "dir -w -p" yields:

argc = 3

argv[0] = "dir"

argv[1] = "-w"

argv[2] = "-p"

 

Your test application takes exactly 1 argument. You need to call it as "cat <filename>" as the output line suggests.  Open up a command prompt and navigate to your exe and run it from the commandline. Or setup the project -> properties -> debugging -> command arguments for your project.

 

2)

ifstream the_file( argv[1] )

That is the actual line that opens a file. You can technically replace the argv[1] with any string you want. The example author wanted to make things easy on you and let you specify the file at the commandline. The test program would thus emulate the unix command "cat <filename>" by opening the file in question and printing it back to standard out.  The ifstream object is the file, and the constructor ifstream(char *) opens the file right there. You can also say:

ifstream file;
file.open( argv[1] );

and it would perform the same action.

Share this post


Link to post
Share on other sites

[quote]I'm not sure if it's referencing files within the program or text files outside of the original source file.[/quote]
The latter. Suppose your program being created is called "myprogram.exe", then you're supposed to call the function from the command line like this:
"myprogram.exe C:\MyExternalTextFile.txt"

If you just write "myprogram.exe" it will show a message on the correct usage and exit. I suppose you don't see that because if you double click your application to open it, it will open the dos-looking box and close very fast, leaving you unable to read the hint in such short time.

Share this post


Link to post
Share on other sites

Okay, well, I've decided I should probably call it a day as far as programming goes. Some of this stuff is just going right over my head. I might just pick up a book or wait until Fall 2013 when I start taking my CS major classes. Well, i'll probably do both. Thanks guys, your info helped but I probably moved a little too fast into programming because a lot of the basic jargon that you guys are using goes over my head lol.

Share this post


Link to post
Share on other sites

If you get swamped with things you don't understand then write a list of them and take them one by one at your own pace. This is something that's going to happen a lot in programming, since there's always new ideas and methodologies coming up. If there's some concept that just boggles you then set it aside for a minute and work more on things that you understand better. Eventually you'll come to the point where you want some kind of functionality or design pattern and you'll suddenly go "hey this sounds just like that X that was confusing me before!" then you re-read the docs for it and it all suddenly makes sense. Also, do not underestimate the power of your subconscious mind as it relates to learning new concepts. If you decide to sit down and learn some hard concept then sit down and read about it, then go take a break or a nap and just chill for a while. Then come back and read it again and try to mess with it a little. Your brain has to build complex new information management structures in order to allow you to think clearly about this stuff, and that takes time. If you're sitting there and bashing your head against the textbook nonstop then you're querying that information before your brain has had a chance to put it into place and you're basically preventing yourself from learning it. Many a time I have read something in a book or on a site and said, "What the hell did I just read?" Then I'd go to bed and get up in the morning and understand it just perfectly.

 

The important thing is to break your workload (yes, learning is work) into manageable chunks. This is true for programs and true for programmers.

Edited by Khatharr

Share this post


Link to post
Share on other sites
It sounds like the tutorial writer is very comfortable using the command line, but may not have considered that his audience may not be. The command line is a great way to accomplish some tasks, but simultaneously trying to get to grips with this alien user interface at the same time as learning some of the key programming concepts is a lot to take on in one go.<br /><br />One option is to simplify again, by hard coding the file path:<pre class="_prettyXprint _lang-code _linenums:NaN">
#include &lt;fstream&gt;
#include &lt;iostream&gt;

using namespace std;

int main ( int argc, char *argv[] )
{
const char *filename = "C:\\test.txt";
ifstream the_file ( filename );
if ( !the_file.is_open() )
{
cout &lt;&lt; "Could not open file: " &lt;&lt; filename &lt;&lt; "\n";
}
else
{
char x;
while ( the_file.get( x ) )
{
cout &lt;&lt; x;
}
}
cin.get();
}
</pre>This will work if you create a text file called C:\test.txt (presuming Windows). You should be able to run it successfully from your IDE.<br /><br />If you get that working and are happy that you understand what it is doing, the next step might be to prompt the user for a filename to read. You can get quite fancy then, for example if the file doesn't open you can prompt the user to choose a different one.<br /><br />Eventually, when you're more comfortable with the basics you might want to head over to the command line and try running your program like that. When you're happy with that, you might want to try the original version of the program and see how that works.<br /><blockquote class="ipsBlockquote"><p>Some of this stuff is just going right over my head.</p></blockquote>That is ok! There is a lot to learn. Don't be put off though, you can do it. Just take it a step at a time.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this