Public Group

#### Archived

This topic is now archived and is closed to further replies.

# Finding files on comp?

This topic is 5155 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

Hey guys is there a way to use ifstream with directories IE: C:\Hello.txt?? When i try to implement it into the ifstream function it obviously gives me an error due to needed quotes in the argument list. this is what ive tried and i get nothing: int main() { string s; ifstream in("C:''\''Hello.txt"); getline(in, s); cout << s; return 0; } thats a simple example and i just cant grab that file out of c: any suggestions? thanks!

##### Share on other sites
The backslash character is used to indicate an escape sequence in a string. To include a single or double quote in a string, you''d do:
"This is a single quote: \'', while this is a double quote:\""

Obviously, this makes it difficult to include a literal backslash in a string. You have to escape the backslash thus:
"This is a Windows path: \"C:\\Program Files\\Microsoft Visual Studio\""

Alternatively, you can use a forward slash for paths. C (and thus C++) has a Unix heritage, so it interprets Unix-styled paths correctly:
ifstream fin("C:/Documents and Settings/Oluseyi/My Documents/Bah.txt");

##### Share on other sites
thanks i beleive its finding the file but now i seem to have some logic errors. what im attempting to do is read from a text file and print a string from it onto my console. this isnt making sense because when i simply do:

ifstream in("Hello.txt");

to open in a read format i can easily store a string and print to the console when Hello.txt is in the Debug/Project folder. the problem presents itself when I try to locate a file (Hello.txt embedded within C: ) and read from it, I get a blank string output (as if nothing is in the file) when there actually is text. what am i doing? thanks.

[edited by - RedRabbit on April 12, 2004 10:39:42 PM]

##### Share on other sites
Simple Explanation Of Code:

#include <iostream>#include <fstream>#include <string>using namespace std;void main() {	char choice;	ifstream in("C:/Program Files/Hello.txt/");	string s;	getline(in, s);	cout << s << endl;	cout << "ending enter a character..." << endl; //Irrelivent dont pay attention to this	cin >> choice; // or this :)			}

##### Share on other sites
Try removing the trailing slash. i.e.:
ifstream in("C:/Program Files/Hello.txt");

The way you have it may be trying to open a directory named Hello.txt.

##### Share on other sites
thanks a ton man!

[edited by - RedRabbit on April 12, 2004 11:06:44 PM]

• 39
• 15
• 9
• 23
• 10