Reading a file - won't open - c++

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")

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.

editing a file using cpp code without creating a new file

Is it possible to edit text in a file using cpp code. Already there is related question on it, but it doesn't solve my problem. Kindly help me out.
I have given a rough code line on this.
seek() through the file and try to replace the contents with new string from that point till the end of line.
I need the "hello" string be placed and must be the end of line.
like if we have new.txt as
ABCDEFGHIJKLMNOPQRST
If I want the file content to be changed as
ABCDEHELLO
I am getting the file content as
ABCDHELLOJKLMNOPQRST
fstream file("new.txt",fstream::in|fstream::out);
file.open();
while(getline(file,str))
{
if(value==strstr())
{
file.seekp(pos);
str.erase(pos,len);//len specifies the value till end of str
str.replace(pos,6,"hello");
char *d=new char[str.length()+1];
strcpy(d,str.c_str());
file.write(d,strlen(d));
delete [] d;
}
}
If I could copy the file contents to the string, manipulate it, then copy to the new file then it is possible.
Is it possible to change the contents in the same file. If so kindly help me out, I am struck in this. If the replacing string is longer than the one actually existing then this works, but if the replacing string is smaller than the one which is actually existing then I am unable to do.
if you case is only one line in the file you can easily separate the I/O process in two stages. Read the file and get the position of the text. then close the file and reopened as out then write the string you want. Note that this will work if you have one line in the file
check the following code
std::string value = "GFGHHFGHH";
std::string str;
std::fstream file("new.txt", std::ios::in);
std::size_t found;
while (file >> str)
{
found = str.find(value);
if (found != std::string::npos)
{
str.erase(value.length() );
str.replace(found, 6, "hello");
}
}
file.close();
file.open("new.txt", std::ios::out);
file << str;
file.close();
You can do it using system call for sed:
string s="sed -i s/hey/ho/g file0102.txt";
system(s.c_str());

Given path to file by user wont work 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.

C++ File not read?

I want to read a file line by line. Did something like
void Parse (string filepath) {
ifstream sourceFile;
sourceFile.open(filepath);
for (string line; getline(sourceFile, line);) {
cout << "1" << endl;
cout << line << endl;
}
}
int main() {
Parse("C:\\test.txt");
getchar();
return 0;
}
Then put some text into C:\test.txt, but when I run, I dont get anything. Why? Not even the "1". I notice no exception if the file is not there too. I suppose that a sign of a problem?
You have to check for success/error manually. Try with ifstream::good():
sourceFile.open(filepath);
if(!sourceFile.good()) {
// do something
If you don't want to check manually, you can enable exceptions:
// call that before open()
sourceFile.exceptions ( ifstream::failbit | ifstream::badbit );
I think you have problems opening the file. I would suggest two things:
check if sourceFile is opened successfully(if (sourceFile))
debug the code and see the code path your code follows.
EDIT: adding the actual solution to the problem in my answer(instead of just a comment) so that people won't miss it:
Here is one more thought - check the file name in its properties. Has happened to me that if windows hides the extension of the file the name is actually test.txt.txt, while what I see displayed is only test.txt.
change your for loop to
for (string line; sourceFile.good();) {
getline(sourceFile, line);
}
This way, you check the validity of your stream in the conditional part of the for, and get the line if the stream good.

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 (: