fstream & ifstream in C++

 I tried to read the file & its contents from the command line. Without much talk, let's get into the topic:

Get the file name

#include <iostream>
using namespace std;

int main(int argc, char* argv[])
{ 
    if (argc > 1) {
        cout << "argv[1] = " << argv[1] << endl; 
    } else {
        cout << "No file name entered. Exiting...";
        return -1; 
    }   
}

sv187@xanthus:~/Documents/lab_assignments/cpp/assignment2b$ ./main input1.txt 
argv[1] = input1.txt
sv187@xanthus:~/Documents/lab_assignments/cpp/assignment2b$ 

Read the file's contents line by line

#include <iostream>
using namespace std;

int main(int argc, char* argv[])
{ 
    if (argc > 1) {
        cout << "argv[1] = " << argv[1] << endl; 
    } else {
        cout << "No file name entered. Exiting...";
        return -1; 
    }   

    ifstream infile(argv[1]); //open the file
    
    if (infile.is_open() && infile.good()) {
        cout << "File is now open!\nContains:\n";
        string line = ""; 
        while (getline(infile, line)){
            cout << line << '\n';
        }   
    
    } else {
        cout << "Failed to open file..";
    }   
    return 0;
}

sv187@xanthus:~/Documents/lab_assignments/cpp/assignment2b$ make
g++ -O0 -g3 -std=c++14   -c -o main.o main.cpp
main.cpp: In function int main(int, char**):
main.cpp:13:21: error: variable std::ifstream infile has initializer but incomplete type
   13 |     ifstream infile(argv[1]); //open the file
      |                     ^~~~
make: *** [<builtin>: main.o] Error 1
sv187@xanthus:~/Documents/lab_assignments/cpp/assignment2b$


#include <iostream>
#include <fstream> // to access the file
using namespace std;

int main(int argc, char* argv[])
{ 
    if (argc > 1) {
        cout << "argv[1] = " << argv[1] << endl; 
    } else {
        cout << "No file name entered. Exiting...";
        return -1; 
    }   

    ifstream inputFile(argv[1]);
    
    if (inputFile.is_open() && inputFile.good()) {
        cout << "File is now open!\nContains:\n";
        string line = ""; 
        while (getline(inputFile, line)){
            cout << line << '\n';
        }   
    
    } else {
        cout << "Failed to open file..";
    }   
    return 0;
}


sv187@xanthus:~/Documents/lab_assignments/cpp/assignment2b$ ./main input1.txt 
argv[1] = input1.txt
File is now open!
Contains:
Hello Shirley
How are you getting on? 
I really want to know your New Year's Resolutions


Comments