+ 6
How can I open and display an existing file on my computer with C/C++?
I tried but it ends in the error handler loop, which means the file does not open, let alone display 😢
21 ответ
+ 4
The program seems correct to me (and works on my machine). Make sure the filename is spelled correctly.
One thing to keep in mind is that file paths are relative to the executable, not the source files. If you compile your program outside of your source folder, the path might be incorrect. If in doubt, try using absolute paths instead.
Unfortunately, this is kind of hard to debug since we have no way of seeing your filesystem.
+ 3
Maybe you could try this tutorial using fstream?
https://www.tutorialspoint.com/read-data-from-a-text-file-using-cplusplus
+ 2
Forche Herod
check if the compiled exe is in the same directory as the text file. If not, move them to the same folder and run the exe again.
I agree with Shadow andTina that the compiler is probably compiling the code to another directory, so it is not finding the text file when it runs.
+ 1
code works fine for me also even with an empty file. most likely a path or file name problem.
btw move read.close(); to the end of else block.
0
This is the code. f.txt is in the same folder as the source code.
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
ifstream read;
read.open("f.txt");
if(!read) {
cout<<"error";
} else {
string line;
while(getline(read, line)) {
cout << line ;
}
}
read.close();
}
0
You can open text files with any text editor. Right-click the file, choose open with notepad or something.
0
I want the compiler to read and display the file contains
0
what error do you get?
are you sure that it is "ifstream"?
0
ifstream is used for reading
0
isn't it "fstream" as the header indicates?
0
I am sure of that
0
fstream is the header which holds datatypes ifstream, ofstream and fstream
0
I receive "error" because the file isn't opening
0
I don't know much c++, sorry...
0
Ok thanks anyway 🙏
0
Thanks for the link
0
But I wanted to read without writing first
0
Thanks guys. I will try when I access my computer
0
Got that. Thanks🙏. I'll retry
- 1
Oh you don't know how it feels to be alone baby