yungman
- 5,741
- 294
Mark44 said:Regarding your post #19:
Line 18 is a cout statement. Do you mean line 13?
Again, this is line 13, and the prototype for openFileIn() is on line 7, not line 11.
Yes, the second argument needs to be a pointer if the argument is a C-string. The parameter is of type char *; the actual argument, "demofile.txt", is of type const char *. There is a bit of type coercion going on here. You could just as well declared the function this way: bool openFileIn(fstream&, const char *); .
Also, your openFileIn() function does not return the file name -- it returns a bool.
Regarding your post #21, your new version of openFileIn() is not as good as the previous version, since the filename is hardcoded in the body of the function. The previous version allows the filename to be passed to the function, so the program could conceivably ask the user to enter the filename at run time.
Before moving on, I would advise that you go back and work with pointers some more. There is a fair amount that you don't understand; namely, the type of a string literal (e.g., "demofile.txt"). Several posts in this thread indicate that you don't have a clear understanding in this area.
I modified my code, this time, you can enter the name of the file you choose. Program will ask you to enter the name. I put in "demofile.txt" and it will run EXCEPT it will give me an error I don't understand that it cannot find the .exe file. But when I choose to continue, it runs and give correct answer. I opened the demofile.txt and verify it was written successfully also.
C++:
//12.5 fstream pass by reference to function
#include <iostream>
#include <fstream>
using namespace std;
const int MAX_LINE_SIZE = 81;
bool openFileIn(fstream&, char[]);
void showContents(fstream&);
int main()
{
char Ar[81];//
cout << " Enter the name and extension of file you want to use: ";
cin >> Ar; cout << "\n\n";//get the name of the file
ofstream outFile;
outFile.open(Ar);
outFile << "This is a test.\n\nAnother test";
outFile.close();
fstream dataFile;
char name[81];
if (!openFileIn(dataFile, Ar))
{
cout << " Fileopen error! \n\n";
return 0;
}
cout << " File opened successfully.\n\n";
cout << " Now reading data from file.\n\n";
showContents(dataFile);
dataFile.close();
cout << " done.\n\n";
return 0;
}
bool openFileIn(fstream& file, char Ar[] )
{
file.open(Ar, ios::in);
if (file.fail())
return false;
else
return true;
}
void showContents(fstream& file)
{
char line[MAX_LINE_SIZE];
while (file >> line)
{
cout << line << " ";
}
cout << "\n\n";
}
The VS is very strange on my computer, I ran this a few times and it did not show error, all of a sudden it start showing error.
Let me know is this better. I still don't have to use pointer. Yes, book have not cover pointer to string literal. I can only follow what the book has, I already went beyond the book on pointers. Actually the book doesn't have pointers to pointers. I learned it from you.
Thanks
Last edited: