Input/Output operations on characters

Viewed 64

I'm learning file handling in C++. I was implementing the exact same code in my Code::Blocks 20.03 as given in one of the programs of the book, but it's displaying no output after line 26, i.e.

cout<<"\nReading the file contents: ";

I've figured maybe these lines are erraneous, but I can't debug how:

while(file){
        file.get(ch);
        cout<<ch;
    }

Here is the full code:

#include <iostream>
#include <fstream>
#include <cstring>
#include <stdlib.h>
using namespace std;

int main()
{
    char String[80];

    cout<<"Enter a string: ";
    cin>>String;

    int len = strlen(String);

    fstream file;
    cout<<"Opening the 'TEXT' file and storing the string in it.\n\n";

    file.open("TEXT",ios::in|ios::out);

    for(int i=0;i<len;i++)
        file.put(String[i]);

    file.seekg(0);
    char ch;
    cout<<"\nReading the file contents: ";
    while(file){
        file.get(ch);
        cout<<ch;
    }
    file.close();
    return 0;
}
3 Answers

The openmode

ios::in | ios::out

will not create a new file if "TEXT" does not exist, but result in an error. Most likely this file does not exist, so you get an error and any subsequent input and output operations on the stream are ignored. You could use

ios::in | ios::out | ios::trunc

to destroy the contents of an existing file or create a new one if the file does not exist.

For further information please consult the table on https://en.cppreference.com/w/cpp/io/basic_filebuf/open where all the different combinations of openmode are detailed.


Lastly, it's always good practice to check if the file was opened:

if(!file) { /* error */ }

You can use is_open() to check if the file was successfully opened and then use an if else loop that will validate if the file can't be found. You don't need to use ios::in|ios::out.

Here's an example that should work:

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

int main () {

  fstream filestr;
  filestr.open ("test.txt");
  if (filestr.is_open())
  {
    filestr << "File successfully open";
    filestr.close();
  }
  else
  {
    cout << "Error opening file";
  }
  return 0;
}

You need to check for end of file inside the loop.

while(file) {
        file.get(ch);
         if(ch == -1) break;
        cout << ch;
    }

Also, try opening the file in write mode first and then close it and open it in read mode.

 cout << "Opening the 'TEXT' file and storing the string in it.\n\n";
 ofstream outfile("TEXT");
 if(outfile.is_open()) {
    for(int i = 0; i < len; i++)
        outfile.put(String[i]);

        outfile.close();
}
 ifstream infile("TEXT");
 char ch;
 if(infile.is_open()) {
   cout << "\nReading the file contents: ";
   while(infile) {
            file.get(ch);
            if(ch == -1) break;
            cout << ch;
    }
        infile.close();
   }
Related