'I am trying to take the contents of fa plain txt file and put it into a char array, then I would like to print it out of the array


  

    #include <stdio.h>

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

int main() {
    int arraySize = 100;
    char file[arraySize];
    fstream myfile;
    
    //open file
    myfile.open("SamplePlainText.txt", ios::binary);
    

    myfile.read(file, sizeof(file));
    myfile.write(file, sizeof(file));

    for(int i=0; i< arraySize; i++) { 
        cout << file[i] << endl; 
    }
}

I am trying to copy the contents of a plain txt file that says "This is a test." into a char array so I can read the information back out of the array using a for loop. Whenever I compile/run the program I am getting a bunch of random numbers and can't figure out where my error is. Any suggestions? (Its only my second semester programming so forgive me if this is not good. This is exactly what I ran on xcode )



Solution 1:[1]

Problems:

  1. The file was not opened for reading or writing and cannot be read or written.

  2. The read was not tested for success before actions were taken on the data read.

  3. The entire buffer was printed regardless of how much, or little, data was read. Writing more data than was read results in printing whatever already existed in the buffer. This often looks like garbage.

Modified and annotated code:

//#include <stdio.h> not required
#include <fstream>
//#include <string> not required
#include <iostream>
//#include <cstdlib> not required
using namespace std;

int main() {
    const int arraySize = 100; // must use constant values to size arrays
    char file[arraySize];
    ifstream myfile; // file opened for input.
    // currently cannot write to file. reading from and writing to the same file 
    // stream is exceptionally hard to get right. For now don't even try. 
    // If you must read and write the same file: 
    //    Read the file into buffer
    //    Modify data in buffer
    //    Close the stream. 
    //    Open the file for writing. 
    //    Write the buffer to the file. 
    //    Close the stream.
    // In this case writing exactly what was read back to the file is pointless, 
    // so I left it out.
    
    //open file
    myfile.open("SamplePlainText.txt",
                ios::binary); // ifstream implies opened for reading
    

    if (myfile.read(file, sizeof(file)))
    { // printing the data read is only meaningful if data was read
        for(int i=0; 
            i< myfile.gcount(); // only print up to number of bytes read 
            i++) {  
            cout << file[i] << endl; 
        }
    }
    else
    {
        cout << "File was not read" << endl;
    }
//    myfile.write(file, sizeof(file));
// left out for now
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1