I've looked up similar posts here, but none seem to be doing the job for my question. I'm basically trying take a sequence of words in a .txt file and put each word in a vector, and printing each value afterwards. For example, we have I love racing cars in array.txt, and I want my vector to have "I" at position 0, "love" at 1 and so on. Unfortunately, the code does not access "array.txt", so it never executes the code in the if condition.
Now I've heard that by using the fstream library it should work just fine, but the file is never found. I suspect that it doesn't work because it cannot find the path, but I have never opened files in C++. Also, I have not put my file anywhere in my project folder.
Some changes I've already tried:
file.open("array.txt");
omitting file.close();
include "C:\array.txt"; (with the # in front)
file.open("C:\array.txt")
And I'm using Windows 10, if this matters.
#include <iostream>;
#include <string>;
#include <vector>;
#include <fstream>;
//#include <"C:\Users\Samer El-Hage\Documents">;
using namespace std;
void main(){
vector<string> v (10);
ifstream file;
file.open("C:\array.txt", ios::in);
if (file.is_open())
{
for (int i = 0; i < 3; i++)
{
file >> v[i];
}
file.close();
}
else cout << "Could not access file.";
for (int i = 0; i < 3; i++)
{
cout << v[i] << " ";
}
}
This code prints "Could not access file."
The file cannot be opened because the file system can't find the file named "[Bell]rray.txt". the character sequence '\a' is the "Make my computer Beep" character.
Use either forward slashes: "C:/array.txt", an escaped backslash: "C:\\array.txt" or a raw string literal: R"(C:\array.txt)"
The file must also exist at the specified location. If you do not provide a drive and just say "array.txt" the location defaults to wherever the executable is (or in an IDE, the Working Directory).
Also, you have unnecessary semi-colons after your includes. (In fact, in a Treat Warnings as Errors setup, this won't compile!)
I got it! I had not put the .txt file in my folder with the source code, which, strangely enough, was not mentioned in my previous search results... I got to search better!
\a simply turns the computer beep on. Try writing "C:\\array.txt" instead in the open call.
Try not calling open explicitly:
ifstream file ("array.txt");
Look at the examples here:1
Related
I have searched for this around the web and here but I can't seem to figure out what I am doing wrong.
I am simply trying get better with file processing and c++.
For practice I am trying to grab a text file from a game folder and make a copy of it.
Here is my code (that can't access the file).
#include <fstream>
#include <iostream>
#include <string>
using namespace std;
int main()
{
//define / open files
ifstream my_input_file;
ofstream my_output_file;
string filepath = "C:/Users/David Laptop/Documents/my games/oblivion/RenderInfo.txt";
my_input_file.open(filepath);
if (my_input_file.is_open())
{
cout << "opened\n";
my_output_file.open("output_file.txt", ofstream::trunc);
char c;
my_input_file.get(c);
while (my_input_file)
{
my_output_file.put(c);
my_input_file.get(c);
}
my_input_file.close();
my_output_file.close();
}
else
{
cout << "FAIL\n";
}
cin.get();
return 0;
}
This seemed to work with both text files and .ini files when in the project directory but I am having issues properly getting to other directiorys?
Any ideas?
thanks!
Your code is perfectly valid and it works - I tried it with my own file instead of yours, in the line
string filepath = "C:/Users/David Laptop/Documents/my games/oblivion/RenderInfo.txt";
So you have not such file or it is not in the given path or you have not such path.
Correct it in that line and it will be OK.
Tip: Find your file in Windows Explorer, press (and keep pressing) Shift) and right-click on this file. From the context menu then choose Copy as path and then paste it to your code. But be carefull - you have to change every backslash (\) to a forward slash (/) (as in your code) or use double backslashes (\\) instead of a single one.
Trying to read a file in C++ using fstream.
But the is_open() function always return 0 result and readline() does not read anything. Please see the code snippet below.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
string line;
ifstream myfile("D:\xx\xx\xx\xx\testdata\task1.in.1");
if (myfile.is_open()) {
while (getline(myfile, line)) {
cout << line << '\n';
}
myfile.close();
}
else
cout << "Unable to open file";
return 0;
}
you think you're opening D:\<somepath>\testdata\task1.in.1
but in fact you're trying to open D:\<somepath><tabulation char>estdata<tabulation char>ask1.in.1 since \t is interpreted as a tabulation.
(like \n is a newline in printf("hello world\n");)
(\x is special too BTW that's not the real path or you would have had another error: error: \x used with no following hex digits which maybe would have talked to you better!)
You have to escape the backslashes like this:
D:\\xx\\xx\\xx\\xx\\testdata\\task1.in.1
Windows also accepts paths like those, more convenient, unless you want to generate batch scripts with cd commands or the like that would require backslashes (/ is used as option switch in batch commands):
D:/xx/xx/xx/xx/testdata/task1.in.1
As NathanOliver stated, you can use the raw prefix if your compiler has C++11 mode enabled (or with --std=c++11)
R"(D:\xx\xx\xx\xx\testdata\task1.in.1)"
Last word: dirty way of getting away with it:
D:\Xx\Xx\Xx\Xx\Testdata\Task1.in.1
Using uppercase in that case would work
because windows is case insensitive
C would let the backslashes as is.
But that's mere luck. A lot of people do that without realizing they're very close to a bug.
BTW a lot of people capitalize windows paths (as seen a lot in this site) because they noticed that their paths wouldn't work with lowercase without knowing why.
I'm new in linux, I'd like to create a file and write something into.
I don't get any error, but the code doesn't create any file...what am I missing?
#include <iostream>
#include <fstream>
int main(){
std::ofstream out("/Home/peter/Dropbox/C++/linux/data.dat", std::ios::out | std::ios::binary);
if(!out)
std::cout << " File isn't open\n" << std::endl;
char s = 'a';
for(int i = 0; i<100; i++)
out.put(s);
return 0;
}
You should add out.close() to the end of your program. This will flush the write buffer to ensure that it was properly written to.
Also, confirm that you actually have (rather, that your program has) permission to create and write files in that directory.
Finally, make sure the path you're writing to is actually correct. As #Adam pointed out in a comment, you probably meant to use /home/... and not /Home/...
I copied and pasted the script, but changed the path, and the code executed successfully. I recommend using out.close() after you are done with the file to close the stream.
You could also use stream operators on the file to write it:
for( int i = 0; i < 100; i++ )
out << s;
Change out.put(s); to out << s;
Secondly once you are done working with files and streams, it is a good practice to close them. It prevents unwanted memory leaks. so put out.close() before return or when you are done working with file.
I am unable to figure out why my code is not able to open and read a file. What am i missing?
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main (int argc, char * const argv[])
{
string line;
ifstream myfile ("input_file_1.txt");
if (myfile.is_open())
{
while (!myfile.eof())
{
getline (myfile,line);
cout << line << endl;
}
}
else
{
cout << "Was unable to open the file" << endl;
}
return 0;
}
The file "input_file_1.txt" is int he same directory as my .cpp file and it has read permissions. I even gave gave it 777 permissions and i was unable to read it.
Can anyone tell me what i am doing wrong? I really cannot figure it out....
Try to use full path for the file
The default location to look for the file is where the executable is , not where the source is.
How and where do you execute your program? From a IDE?
Can you run the program from the same directory where you have your text file.
Another possibility is to use an absolute path to the file.
If you don't specify a path, the library will attempt to load the file from the current directory. You need to make sure that this is where the file is.
Also, you might not be able to open the file if it is opened in an exclusive manner by another program. Ensure that it is not still open in another program such as your editor.
Other Problems:
Explicitly testing for EOF is usually wrong.
The last valid read (getline() here) reads up-to but no past the EOF. You then print the line. Then restart the loop. These test for eof() does not fail (as it has not read past the EOF). You then enter the loop body and attempt to read the next line (with getline()) this fails as there are 0 bytes left to read (thus leaving the value of line in an undefined state). You then print out line (undefined value) and a newline character.
while (!myfile.eof())
{
getline (myfile,line);
cout << line << endl;
}
A correct version of a loop reading a file is:
while (getline (myfile,line))
{
cout << line << endl;
}
This works because the getline() returns a reference to a stream. A stream used in a boolean context (like a while condition) tests to see if the stream is in a bad state (ie it test for EOF and other bad situations) and returns an object that can be used correctyl in the context. If the state of the stream is OK then a successful read has happened and the loop is entered (thus allowing you to print the line).
The binary created from your code (including your cpp) is executed somewhere different from your code is, probably a "bin"-folder. You schould put the file into the same folder as your executable.
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 (: