C++ reading a file in binary mode. Problems with END OF FILE

Asked
Active3 hr before
Viewed126 times

9 Answers

90%

I am learning C++and I have to read a file in binary mode. Here's how I do it (following the C++ reference):, @bash.d But he's not using the return value to test for end of file. It's not idiomatic, but the standard does say that if there is no character to extract, istream::get() should set failbit. (I would also expect it to set eofbit, under the more general definition of eofbit.) – James Kanze May 8 '13 at 8:30 ,So, I am reading the file byte per byte till in.good() is true. I put some cout at the end of the while in order to understand what's happening, and here is the output:,I've eventually figured this out. Apparently it seems the problem wasn't due to any code. The problem was gedit. It always appends a newline character at the end of file. This also happen with other editors, such as vim. For some editor this can be configured to not append anything, but in gedit this is apparently not possible. https://askubuntu.com/questions/13317/how-to-stop-gedit-gvim-vim-nano-from-adding-end-of-file-newline-char

Secondly, you are reading in binary, so you shouldn't use formatted streams. You should use fstream::read:

// read a file into memory
#include <iostream>     // std::cout
#include <fstream>      // std::ifstream

int main () {

  std::ifstream is ("test.txt", std::ifstream::binary);
  if (is) {
    // get length of file:
    is.seekg (0, is.end);
    int length = is.tellg();
    is.seekg (0, is.beg);

    char * buffer = new char [length];

    std::cout << "Reading " << length << " characters... ";
    // read data as a block:
    is.read (buffer,length);

    if (is)
      std::cout << "all characters read successfully.";
    else
      std::cout << "error: only " << is.gcount() << " could be read";
    is.close();

    // ...buffer contains the entire file...

    delete[] buffer;
  }
  return 0;
}
load more v
88%

I am learning C++and I have to read a file in binary mode. Here's how I do it (following the C++ reference):,The data buffer being transferred must be aligned on a memory boundary that is a multiple of the block size (use posix_memalign),The length of the data to be transferred must be a multiple of the block size,A filename beginning with / is an absolute name, and is relative to the root of the filesystem.

I am learning C++and I have to read a file in binary mode. Here's how I do it (following the C++ reference):

unsigned values[255];
unsigned total;
ifstream in ("test.txt", ifstream::binary);

while ( in .good()) {
   unsigned val = in .get();
   if ( in .good()) {
      values[val]++;
      total++;
      cout << val << endl;
   }
}

in .close();

So, I am reading the file byte per byte till in.good() is true. I put some cout at the end of the while in order to understand what's happening, and here is the output:

marco @iceland: ~/workspace/huffman$. / main
97
97
97
97
10
98
98
10
99
99
99
99
10
100
100
10
101
101
10
221497852
marco @iceland: ~/workspace/huffman$

Now, the input file "test.txt" is just:

aaaa
bb
cccc
dd
ee
load more v
72%

ios::binary This causes the file to be accessed as a binary file. Most likely you will need to set this option. If you forget to set this option, many strange problems will occur when reading certain characters like `end of line' and `end of file'.,This function accepts no parameters, but returns the location given in bytes from the beginning of the file where the file pointer is currently sitting. The next read or write will take place from this location. , It is the responsibility of the programmer to make sure that the buffer is large enough to hold all the data that is being read. The following code segment would probably result in a crash unless the size of a integer was 7 bytes (unlikely number):,The insertion and extraction operators (i.e. << and >> are meant to be used by programs for writing to and reading from text files; it is assumed that the programmer is familiar with the differences between these two file formats.

void open(const char * filename[, int mode][, int prot]);
load more v
65%

If an error occurs while writing (for example, if you run out of disk space), the stream is placed in an error state. Such errors are not as common as read errors, and are often not checked. , fstream for reading and writing from/to one file.,There is also a variant of seekp that allows you to specify a position relative to the current put pointer location, or relative to the end of the file.  ,There is also a variant of seekg that allows you to specify a position relative to the current get pointer location, or relative to the end of the file. 

stat
    #include <sys /stat.h>
       ...
       struct stat results;
       
       if (stat("input.bin", &results) == 0)
           // The size of the file in bytes is in
           // results.st_size
       else
           // An error occurred
load more v
75%

Problem Statement : To read and write a File in C++. Examples: ,Priority Queue in C++ Standard Template Library (STL),Read/Write Class Objects from/to File in C++,Unordered Sets in C++ Standard Template Library

Problem Statement : To read and write a File in C++. 
Examples: 

Input:
   Welcome in GeeksforGeeks.Best way to learn things. -
   1
Output:
   Welcome in GeeksforGeeks.Best way to learn things.
load more v
40%

Writing a binary file in C++,Reading and Writing to text files in Python,Reading a Text file in java,Reading and Writing to text files in C#

Syntax of write method

ostream & write(const char * , int);
load more v
22%

File handling in C++ is a mechanism to store the output of a program in a file and help perform various operations on it. Files help store these data permanently on a storage device. ,File created and data got written to file,What is File Handling in C++?,Writing the data to the created file.

Example:

#include<iostream>

   #include<fstream>
load more v
60%

The fopen() function is not supported for files that are opened with the attributes type=record and ab+, rb+, or wb+,The fopen() function generally fails if parameters are mismatched.,If a text file does not exist, you can create one using the following command:,If a binary file does not exist, you can create one using the following command:

Format

#include <stdio.h>
   FILE *fopen(const char *filename, const char *mode);

/* Create a file that is tagged with CCSID 37 */
if ((fp = fopen("/MYFILE", "w, o_ccsid=37")) == NULL) {
   printf("Failed to open file with o_ccsid=37\n");
}

fclose(fp);

/* Now reopen the file with CCSID 13488, because your application
 wants to deal with the data in UNICODE */

if ((fp = fopen("/MYFILE", "r+, o_ccsid=13488")) == NULL) {
   printf("Failed to open file with o_ccsid=13488\n");
}
/* Turn buffering off because read functions do not work when
buffering is on */

if (setbuf(fp, NULL, _IONBF, 0) != 0) {
   printf("Unable to turn buffering off\n");
}
/* Because you opened with o_ccsid = 13488, you must provide
all input data as unicode.
If this program is compiled with LOCALETYPE(*LOCALEUCS2),
L constrants will be unicode. */

funcreturn = fputws(L "ABC", fp); /* Write a unicode ABC to the file. */

if (funcreturn < 0) {
   printf("Error with 'fputws' on line %d\n", __LINE__);
}
/* Because the file was tagged with CCSID 37, the unicode ABC was
converted to EBCDIC ABC when it was written to the file. */
#include <stdio.h>
#define  MAX_LEN  60
 
int main(void)
{
   FILE *stream;
   fpos_t pos;
   char line1[MAX_LEN];
   char line2[MAX_LEN];
   char *result;
   char ch;
   int num;
 
   /* The following call opens a text file for reading.   */
   if ((stream = fopen("mylib/myfile", "r")) == NULL)
      printf("Could not open data file\n");
   else if ((result = fgets(line1,MAX_LEN,stream)) != NULL)
           {
            printf("The string read from myfile: %s\n", result);
            fclose(stream);
           }
 
   /* The following call opens a fixed record length file */
   /* for reading and writing.                            */
   if ((stream = fopen("mylib/myfile2", "rb+, lrecl=80,  \
                 blksize=240, recfm=f")) == NULL)
         printf("Could not open data file\n");
   else {
         fgetpos(stream, Point-of-Sale);
         if (!fread(line2,sizeof(line2),1,stream))
            perror("fread error");
         else printf("1st record read from myfile2: %s\n", line2);
 
         fsetpos(stream, Point-of-Sale);     /* Reset pointer to start of file */
         fputs(result, stream);     /* The line read from myfile is   */
                                    /* written to myfile2.            */
         fclose(stream);
        }
}
load more v
48%

Basics of C++: Structure of a program Variables and types Constants Operators Basic Input/Output ,Standard library: Input/output with files ,When the file is closed: before closing a file, all buffers that have not yet been flushed are synchronized and all pending data is written or read to the physical medium.,fstream: Stream class to both read and write from/to files.

123456789101112
load more v

Other "undefined-undefined" queries related to "C++ reading a file in binary mode. Problems with END OF FILE"