4

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;
}
Arju Aman
  • 412
  • 1
  • 5
  • 15
  • My first thought is: try `cout << std::flush;` before you close the file? Not sure if it will resolve, as I might have missed something. – user123 Jun 29 '20 at 12:42
  • 1
    `while(file)` looks bad like [c - Why is “while ( !feof (file) )” always wrong? - Stack Overflow](https://stackoverflow.com/questions/5431941/why-is-while-feof-file-always-wrong) – MikeCAT Jun 29 '20 at 12:51
  • 1
    Check if the file was opened: `if(!file) { /* error */ }` – Lukas-T Jun 29 '20 at 12:53

3 Answers3

3

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 */ }
Lukas-T
  • 11,133
  • 3
  • 20
  • 30
  • Thanks it worked, but there's one flaw, the last letter I type in my string is repeated twice, it goes like this: >>Enter a string: Hiccup >>Opening the 'TEXT' file and storing the string in it. >>Reading the file contents: Hiccupp //like a n extra 'p' got appended at the last – Arju Aman Jun 29 '20 at 15:02
  • 1
    Yes, to fix this change just ` while(file){ file.get(ch); cout< – Lukas-T Jun 29 '20 at 15:29
1

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;
}
Noah670
  • 81
  • 5
  • I used it to check, it's opening fine, as @churill answered, addind ios::trunc at refposition helped. Thank you for your time! – Arju Aman Jun 29 '20 at 15:06
1

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();
   }
Amal K
  • 4,359
  • 2
  • 22
  • 44
  • 1
    I've tried this way, it works, but what I was trying was to get the result using a single fstream object only! Thanks btw! – Arju Aman Jun 29 '20 at 15:04