C++ [HELP]

How to Create a Program in C++ displaying the content
of a File? . I have no idea yet. Help ^^
is this working ?

#include <iostream>
#include <fstream>
using namespace std;

int main () {
ofstream myfile;
myfile.open ("example.txt");
myfile << "Writing this to a file.\n";
myfile.close();
return 0;
}
Why don't you compile and run it and find out? :)
ofstream is output stream.

In other words you use ofstream when you want to write data to a file, not read it.
To read you would use ifstream.

I dont normally write code for people but I'll cut you some slack since you're a beginner.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

//declaring all the libraries we will be using

int main() {

ifstream input("test.txt");

//opening the file with ifstream because we are trying to read it

string line;

while (getline (input,line)) {

cout << line << endl;

}

//we use this loop to read the file line by line and output each line as we go

return 0;
}

A few things about the above, why use ifstream not fstream? and I'm pretty sure you should check that it opens correctly rather than assuming. Also, can't you directly use the bit shift operators from stream to stream?
Ok, I don't use fstream that often, but Im pretty sure fstream is just the name for the library, not an actual type.

Just as iostream is the name of the library which includes things like cout and cin.

Your absolutely right, but I generally only would do that is the file is complicated, and could potentially be corrupted.

And lastly, I'm not sure if bit shift operators are usable with file reading.
Whenever I have looked up code for opening files, I only find this 'getline' technique.

But you're obviously free to look into it!
fstream is a type, and can be used for both read and write operations.

Though unlike <iostream> which can be seperated into <ostream> and <istream> I don't think <fstream> can be split? Would need a second opinion though.

EDIT:

And yes, bit shift operators ( Though I think named "stream extraction operators" when working with streams ) can be used with any stream, such as file, display and string streams.
Last edited on
Topic archived. No new replies allowed.