Computer Science Canada

Linking a File to a C++ Program

Author:  ssy [ Sun Jun 20, 2010 7:14 pm ]
Post subject:  Linking a File to a C++ Program

I have to write a C++ program that opens a file and counts all the whitespace separated words in that file.

I am using GNU C++ compiler on Mac, using the terminal instead of an IDE. What command do I use to link a file to be opened in my C++ program at the command line? And I don't have to use an ifstream object right? Since I am not really opening up a file from within my program? Kind of confused...

Author:  TerranceN [ Sun Jun 20, 2010 7:43 pm ]
Post subject:  RE:Linking a File to a C++ Program

Usually you don't link the file to your program, you open it with ifstream. ifstream does not require the file to be "within [your] program." Though I'm pretty sure you can include any data you want in your .exe, I just don't have a clue how to do it.

I'm sure <a href=http://www.cplusplus.com/doc/tutorial/files/>this</a> could explain it a lot better.

Author:  ssy [ Sun Jun 20, 2010 9:39 pm ]
Post subject:  Re: Linking a File to a C++ Program

Thanks for the reply, but the reason I ask is because this program is supposed to be able to open ANY text files within the same directory. All the example codes I have seen only opens a specific file.

This is supposed to be the answer:

#include <iostream>
#include <string>
using namespace std;

int main() {
int nwords = 0;
string word;

while (cin >> word) {
++nwords;
}

cout << "Number of words = " << nwords << endl;
}

But I don't know how to execute that by linking a file to it.

Author:  Monduman11 [ Sun Jun 20, 2010 9:42 pm ]
Post subject:  RE:Linking a File to a C++ Program

umm quick question whats the diffference between #include <iostream> and #include <iostream.h>, oh and what about #include <conio.h>
cause i learned these with my teacher last year but she didint fully explain what they were for

Author:  ssy [ Sun Jun 20, 2010 9:53 pm ]
Post subject:  Re: Linking a File to a C++ Program

Never mind, I figured it out!

For anyone who cares, I just need to link the text file to the a.out file, with this command: ./a.out < textfile.txt

And for Monduman11:
#include <iostream.h>
is equal to
#include <iostream>
using namespace std;


Something to do with the transition from C to C++ and the way headers files are included.

Author:  Monduman11 [ Sun Jun 20, 2010 9:54 pm ]
Post subject:  RE:Linking a File to a C++ Program

ah kk thanks and im guessing #include<conio.h> is the same thing


: