Is it possible to read from a file without fstream?

Can lines of text be read from a file without using fstream? More specifically, can it be read with only <sstream>, <string>, and <iostream>?
In my experience, I would say no, you either have to use fstream or ifstream to read from a file and ofstream to read to a file.
What about from standard in? If I '$ myprog <input.txt >'
Last edited on
Sure, if you redirect the input, you're now going through istream rather than fstream.

The >> and getline methods work the same regardless.

What's the question?
The question was if there was something other than fstream I could use to read a file. I didn't learn that I could use standard in on a file until after I had asked the question. I brought it up to make sure the information was correct.
Last edited on
FILE * variables?
> More specifically, can it be read with only <sstream>, <string>, and <iostream>?
> something other than fstream I could use to read a file.

std::cin reads from standard input; we can set it up (redirect) so that standard input comes from the file.
https://en.wikipedia.org/wiki/Redirection_(computing)#Basic

For example:

1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>
#include <string>
#include <iomanip>

int main()
{
    int line_number = 0 ;
    std::string line ;
    
    while( std::getline( std::cin, line ) ) // for each line read from stdin
        std::cout << std::setw(4) << ++line_number << ".  |" << line << '\n' ; 
}

echo && g++ -std=c++17 -O3 -march=native -Wall -Wextra -pedantic-errors main.cpp
./a.out < main.cpp #standard input is redirected; it now comes from the file main.cpp
echo && echo ============ && echo
clang++ -std=c++17 -stdlib=libc++ -O3 -march=native -Wall -Wextra -pedantic-errors main.cpp -lsupc++
./a.out < main.cpp #standard input is redirected; it now comes from the file main.cpp

http://coliru.stacked-crooked.com/a/7932cfc5850651e3
I was just going to ask another question about redirection, but you just answered it. Thank you.
Registered users can post here. Sign in or register to post.