Absolute Path Reference

I am trying to open a file and print the contents of the file to the terminal window. It works when I put the file right in the directory with the Solution but not if the file is out on my desktop and I use the full path. Any ideas what I am doing wrong? Here is the code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int OpenFile(){
	fstream SampleFile;
	SampleFile.open ("C:\\Users\\scooke\\Desktop\\sample.csv");
	if (SampleFile.is_open())
	{
		string line;
		while (getline (SampleFile,line))
		{
			cout<<line<<endl;
		}
		SampleFile.close();
	}
	else
	cout <<"Could not open file."<<endl;
	
	return 0;
}

int main()
{
	OpenFile();
	return 0;
}
Are you sure that the path is 100% correct?
Yes,

Here is a screenshot of the properties window for the file.

http://i.imgur.com/IsMs4gL.png
What error does open() return?

Try moving sample.csv to C:\ and see if the code works there. Then move it down one directory at a time.

It might also be possible that your compiler wants forward slashes (/) instead of backslashes (\) for the path delimiter, but I'm reaching here.

Dave
Thanks for the reply. I've added the file to the C Drive folder and tried "C:\\sample.csv" and "C://sample.csv" and neither worked. It still continues to work from the local directory. Very strange. I am not getting any compile errors, I am just getting the else message that I've asked for in the event that the file is not successfully opened which is "Could not open file."

Very strange. Any other ideas?
Ugh. Does fstream set errno? You could print it out to see why it's failing. Looking at the reference, I don't see that open() provides any details on why it might fail.

Are the file permissions read-only? I bet that would do it. If you're just reading the file, use ifstream instead of fstream, which supports both reading and writing.
Topic archived. No new replies allowed.