Given path to file by user wont work c++ - c++

I am trying to get a path from the user, then insert it into ifstream, but it doesn't work. My file is located at: C:\test.txt I used double backslash, but it is still not working.
string pot;
cout<<"GIVE PATH TO FILE:"<<endl;
getline(cin,pot);
//pot="C:\\test.txt";
string line;
string besedilo[2];
short i=0;
ifstream myfile (pot.c_str());
if (myfile.is_open())
{
while ( getline (myfile,line) )
{
besedilo[i]=line;
i=i+1;
}
myfile.close();
}

I've tried your code... And it worked perfectly for a .txt file on my D: disk.
Just be sure you used double slash and properly wrote path. I don't see any other option why it's not working like you want.

You could use Boost Filesyetm. It's platform agnostic and handles all those backslash, forward-slash, escape-slash headaches.

Related

How to read text from file itno standard string cpp

I am trying to read about 2 lines from a file of text into a std::string in c plus plus. I have looked through several answers and found none that work on my device. Can anyone tell me what I am doing wrong? The method is currently returning a null string, and doesn't correctly open the file or read it at all.
std::string readFile(std::string filename) {
std::ifstream infile;
infile.open(filename);
std::string output;
if (infile.is_open()) {
while(infile.good()) {
infile >> output;
}
}
infile.close();
return output;
}
Not sure what file you are trying to open but that's a completely separate problem. The code you've written will open a file if you give it a path to a file that it can open. Check your current working directory and confirm the path is correct.
Even after you solve that problem, you're going to have more problems though.
I expect that you are confused because you are repeatedly overwriting output with this line:
infile >> output;
perhaps you meant to declare output as a std::stringstream
And for me it doesn't return an empty string, it returns the last word of the file. I guess it depends what's in your file.

How to read a File and save specific occuring strings?

I need to read a file, which is an .asc document using QT Framework.
I need to check the file for specific Strings, for example "(Name)".
The Numbers after the specific String have to be saved in another .txt file.
So I tried to use a for loop connected with a getline() statement, whilst an if statement should be checking if the predefined String was found already.
If the String was found I am using a string variable .assign() method to input the whole matching line to another string.
But sadly it is still not working, maybe there is a logical failure, so I am asking for your help!
std::string line;
std::string search = "(Name)";
std::string content;
std::ifstream ifs("C:/PROG/EMS/LD1/analyse_led");
for(unsigned int curLine = 0; std::getline(ifs, line); curLine++) {
if (line.find(search) != std::string::npos) {
content.assign( (std::istreambuf_iterator<char>(line) ),
(std::istreambuf_iterator<char>() ) );
}
}
Of course I implemented all related include files above, thanks for your help!
If you need more information let me know in the comments.
content and line are both std::strings, just do
content = line;
or
content = std::move(line);
if you don't need to do anything else with line afterwards. (line will be empty after this).
I'm not sure what you are trying to achieve with istreambuf_iterator, but I'm sure it isn't going to work...

Problems using getline()

I'm running out of hair to pull out, so I thought maybe someone here could help me with this frustration.
I'm trying to read a file line by line, which seems simple enough, using getline(). Problem is, my code seems to keep ignoring the \n, and putting the entire file into one string, which is problematic to say the least.
void MakeRandomLayout(int rows, int cols)
{
string fiveByFive = "cubes25.txt";
string fourByFour = "cubes16.txt";
ifstream infile;
while (true) {
infile.open(fourByFour.c_str());
if (infile.fail()) {
infile.clear();
cout << "No such file found";
} else {
break;
}
}
Vector<string> cubes;
string cube;
while (std::getline(infile, cube)) {
cubes.add(cube);
}
}
Edits: Running OSX 10.7.
The infinite loop for the file is unfinished, will eventually ask for a file.
No luck with extended getline() version, tried that earlier.
Same system for dev and build/run.
The text file i'm reading in looks as follows:
AAEEGN
ABBJOO
ACHOPS
AFFKPS
AOOTTW
CIMOTU
DEILRX
DELRVY
DISTTY
EEGHNW
EEINSU
EHRTVW
EIOSST
ELRTTY
HIMNQU
HLNNRZ
Each string is on a new line in the file. The second one that I'm not reading in is the same but 25 lines instead of 16
Mac software recognizes either '\r' or '\n' as line-endings, for backward compatibility with Mac OS Classic. Make sure that your text editor hasn't put '\r' line endings in your file when your processing code is expecting '\n' (and verify that the '\n' characters you think are in the middle of the string aren't in fact '\r' instead.
I suspect that you are failing to display the contents of Vector correctly. When you dump the Vector, do you print a \n after each entry? You should, because getline discards the newlines on input.
FYI: the typical pattern for reading line-by-line is this:
Vector<string> cubes;
string cube;
while(std::getline(infile, cube)) {
cubes.add(cube);
}
Note that this will discard the newlines, but will put one line per entry in Vector.
EDIT: For whatever it is worth, if you were using an std::vector, you could slurp the file in thusly:
std::ifstream ifile(av[1]);
std::vector<std::string> v(
(std::istream_iterator<std::string>(ifile)),
std::istream_iterator<std::string>());

Reading a file - won't open

I am trying to open a file in C++ but it seems to be giving me a bit of hassle, here is the code that deals with opening the file so far:
void CreateHistogram(string str_file, vector<HistogramWord> &result) {
string line;
long location;
HistogramWord newWord;
const char * filename = str_file.c_str();
//ifstream myfile (str_file.c_str());
ifstream myfile (filename);
//myfile.open(filename);
if (myfile.is_open()) {
while (myfile.good()) {
getline(myfile, line);
line = clarifyWord(line);
Okay, just for a bit of explanation, HistogramWord is a struct that is defined in the header and from what I have read in the online documentation, the filename has to be of type const char *, so that is what I have done. Converted str_file to be a const char *.
Now, I have tried a few different things which is why some of the code is commented out. When it gets to the line if (myfile.is_open()), it always evaluates to false. Anyone seem to know why?
Thanks,
Brandon
OK IO 101
If you don't give the complete filepath but only the filename then the current working directory will be appended to the filename.
So if your .exe is in C:\temp and you call your program from this directory and your filename is test.txt then the complete filename in this case will be C:\temp\test.txt
This will only work if the .exe and the test.txt are both under C:\temp.
In all other cases it will fail. You could create the absolute path by using win API or the linux equivalent - I don't know what platform you are on.
Now in order to read a succsfully opened file this will suffice :
void CreateHistogram(string str_file, vector<HistogramWord> &result) {
string line;
long location;
HistogramWord newWord;
ifstream myfile (str_file.c_str());
if (myfile.is_open()) {
while (getline(myfile, line)) {
line = clarifyWord(line);
}
else{
//throw exception, print error message etc
throw std::exception(std::string("Couldn't open file : " + str_file).c_str());
}
}
edit : Thanks # Shahbaz
My best guess is that Windows is "hiding extensions for known file types" so the name of the file is actually different than what you have put in windows. For example if it's a .txt file, and you name it test.txt, the actual name would be test.txt.txt which is quite a stupid thing windows does.
To change this, go to My Computer -> Toold -> Folder Options -> And uncheck the box that says "Hide extensions for Known File Types". This is for XP. If you have another windows it should be more or less the same path. If you don't see the toolbar, try ALT+t (tools) or ALT+f (file) to make it appear.
This problem give quite many of us a trouble in the first semester of college.
What fixed it for me was using forward slashes instead of double backslashes in my filepath.
e.g.
inFile.open("path/to/file.txt")
instead of
inFile.open("path\\to\\file.txt")

Open file by its full path in C++

I want the user to give me the full path where the file exists and not just the file name. How do I open the file this way?
Is it something like this:
ifstream file;
file.open("C:/Demo.txt", ios::in);
This doesn't seem to work.
Normally one uses the backslash character as the path separator in Windows. So:
ifstream file;
file.open("C:\\Demo.txt", ios::in);
Keep in mind that when written in C++ source code, you must use the double backslash because the backslash character itself means something special inside double quoted strings. So the above refers to the file C:\Demo.txt.
You can use a full path with the fstream classes. The folowing code attempts to open the file demo.txt in the root of the C: drive. Note that as this is an input operation, the file must already exist.
#include <fstream>
#include <iostream>
using namespace std;
int main() {
ifstream ifs( "c:/demo.txt" ); // note no mode needed
if ( ! ifs.is_open() ) {
cout <<" Failed to open" << endl;
}
else {
cout <<"Opened OK" << endl;
}
}
What does this code produce on your system?
The code seems working to me. I think the same with #Iothar.
Check to see if you include the required headers, to compile. If it is compiled, check to see if there is such a file, and everything, names etc, matches, and also check to see that you have a right to read the file.
To make a cross check, check if you can open it with fopen..
FILE *f = fopen("C:/Demo.txt", "r");
if (f)
printf("fopen success\n");
For those who are getting the path dynamicly... e.g. drag&drop:
Some main constructions get drag&dropped file with double quotes like:
"C:\MyPath\MyFile.txt"
Quick and nice solution is to use this function to remove chars from string:
void removeCharsFromString( string &str, char* charsToRemove ) {
for ( unsigned int i = 0; i < strlen(charsToRemove); ++i ) {
str.erase( remove(str.begin(), str.end(), charsToRemove[i]), str.end() );
}
}
string myAbsolutepath; //fill with your absolute path
removeCharsFromString( myAbsolutepath, "\"" );
myAbsolutepath now contains just C:\MyPath\MyFile.txt
The function needs these libraries: <iostream> <algorithm> <cstring>.
The function was based on this answer.
Working Fiddle: http://ideone.com/XOROjq
A different take on this question, which might help someone:
I came here because I was debugging in Visual Studio on Windows, and I got confused about all this / vs \\ discussion (it really should not matter in most cases).
For me, the problem was: the "current directory" was not set to what I wanted in Visual Studio. It defaults to the directory of the executable (depending on how you set up your project).
Change it via: Right-click the solution -> Properties -> Working Directory
I only mention it because the question seems Windows-centric, which generally also means VisualStudio-centric, which tells me this hint might be relevant (: