#include <fstream>
#include <iostream>
#include <string>
#include <cstdlib>
using namespace std;
int main(){
ifstream file;
string fileName ="file.txt";
file.open(fileName.c_str());
if (!file){
cout << "Failed to open file" << endl;
return -1;
}
string newLine;
while(std::getline(file, newLine)) {
cout<<newLine<<endl;
}
return 1;
}
If you do not specify an absolute pathname to the file, the filename
is relative to the current working directory when you start the
project. I believe that in VS, by default, this is the directory the
EXE ends up in -- which is your output directory (like "Release" or
"Debug"), not the project directory. You could try putting it there.
You could also go to your Project Properties -> Configuration
Properties -> Debugging and change "Working Directory" to the
directory that contains your file. VS will then change to that
directory before starting your program if you run it from the IDE.
Another option is to call SetCurrentDirectory() before opening the
file to set the current working directory to whatever.
Yet another option is to specify the absolute path to the file in your
program:
string fileName ="c:\\wherever\\file.txt";
In any case, if the filename is a relative path it must be in the
current working directory. Upon starting the program, VS sets the
current working directory to the output path by default (I think). So
pick any solution that puts the file in the current working directory.
That said, this question is not on topic for comp.lang.c++. In the
future you'll probably want to head to one of the microsoft.public.*
newsgroups instead. This newsgroup is for specific questions about the
syntax and semantics of the C++ language itself.
Jason
On Mar 19, 10:33 pm, "jason.cipri...@gmail.com"
> > }- Hide quoted text -
>
> - Show quoted text -
Maybe. Your code looks relatively simple, though. I don't know what
else to tell you. Perhaps as a test, try:
#include <stdio.h>
#include <string.h>
#include <string>
using namespace std;
int main () {
FILE *file;
string fileName ="file.txt";
file = fopen(fileName.c_str(), "rt");
if (!file) {
perror("Could not open file");
return -1;
}
// ...
}
At least with fopen() you can get a reasonable error message (if it
says "file not found", then you know the problem is that it's not in
the path you think it is in).
Incidently, if anybody knows how to get a reliable error message from
an ifstream after a failed operation, I'd love to know. It's always
kind of bothered me.
Jason
Whoops, you don't need the string.h.