answersLogoWhite

0

The following code demonstrates how the end of file can be detected. Note that you do not test std::istream::eof() directly. The eof flag is only set when you read past the end of a file, not when you read the last character in a file. That is, if the file has three characters and you extract three characters, eof is not set at that point. It is only set when you attempt to read another character and there is no character there. At that point you are past the end of the file and the flag is set.

#include<iostream>

#include<fstream>

int main()

{

char * filename = "test.txt";

// create a 3-character file

std::ofstream outfile;

outfile.open (filename, std::ios::out);

outfile << "ABC";

outfile.close();

std::ifstream infile;

infile.open (filename, std::ios::in);

char ch;

while (infile.get(ch))

{

std::cout << ch;

std::cout << "\tEOF flag is " << (infile.eof()?"":"not") << " set\n";

}

std::cout << "EOF flag is " << (infile.eof()?" ":"not ") << "set\n";

infile.close();

}

User Avatar

Wiki User

11y ago

What else can I help you with?

Related Questions

How do you detect an empty file in a c program?

Seek to the end of the file (fseek) and check how many bytes are in the file If the byte count is zero the file is empty.


How the end of file can be detected in c plus plus?

Use the istream::eof() method.


How to complete this C plus plus End Of File controlled while loop program?

Add the missing parts.


How do you create .exe file in c plus plus?

You can create an exe-file from your C++ source, if you have a compiler.


How do you open a file in c plus plus?

fopen()


Is there a file concept in c plus plus?

No. The standard does not define nor require a file concept.


Can you rewrite a cuda file in c c plus plus language?

Yes, you can rewrite a cuda program originally written in c in c plus plus.


What is a scatter file in c or c plus plus programming?

Scatter File is a linker script file used by RVCT/Keil for ARM processors. It is used by arm linker.


Explain any six file commands in C plus plus?

There's no commands in C++.


How do you concatinate two files in c plus plus?

Copy the first file then append the second file to the copy.


Is it possible to skip to a new line when reading from a file in c plus plus?

To skip to a new line when reading from a file, assuming you are using a sequentially organized file, the usual case, you need to read and discard characters until you encounter the end-of-line character.


How do you convert a notebook file to a c plus plus file?

There are no "notebook files"; C++ sources are ordinary text files. When you save a file from NotePad, select File/SaveAs and select 'file type: all', then enter the name, e.g. myprogram.cpp