0

I'm trying to read character by character from a text file until EOF, put them into a character array, so that I can manipulate it after. Compiled with g++ without errors, and when run, I'm prompted for the input file but then it just hangs.

int main (int argc, char *argv[]) {
    string filename;
    ifstream infile;

    char *cp, c[1024];
    memset (c, 0, sizeof(c));
    cp = c;

    cout << "Enter file name: " << endl;
    cin >> filename;

    //open file
    infile.open( filename.c_str() );

    //if file can't open
    if(!infile) {
        cerr << "Error: file could not be opened" << endl;
        exit(1);
    }

    while (!infile.eof()); {
        infile.get(c, sizeof(infile));
       // get character from file and store in array c[]
    }
}//end main
dda
  • 6,030
  • 2
  • 25
  • 34
harman2012
  • 103
  • 3
  • 8

3 Answers3

1

You should try the istream::read() method rather than get(). This will help resolve any buffer overruns:

unsigned int chars_read = 0;
//...
// Read in the file.
if (!infile.read(c, sizeof(c))
{
    // Handle the read error here.
    // Also check for EOF here too.
}

// Obtain the number of characters actually read.
chars_read = infile.gcount();
Thomas Matthews
  • 56,849
  • 17
  • 98
  • 154
0

First off, you don't want to test for eof()! Somehow I start to feel like Don Quixote having found my windmills. However, I do know that you need to check that the input was successful after trying to read it because before attempting to read the stream can't know whether it will be successful.

You program actually doesn't hang! It just waits for you to enter sizeof(infile) characters or end the input (e.g., using Ctrl-D on UNIXes and Ctrl-Z on Windows). Of course, this may look remarkable like a hanging program. You can verify that this is, indeed, the problem by using a smaller size, e.g., 4. Of course, sizeof(infile) is nearly as good as a small random number: It is the size of an object of type std::ifstream and who can tell what that is? You probably meant to use sizeof(c) to make sure that the call to get(c, n) won't write more character than can fit into c.

Dietmar Kühl
  • 150,225
  • 13
  • 225
  • 380
  • The OP also needs to check the amount of characters read vs. the capacity of the array. Otherwise a buffer overflow will occur. – Thomas Matthews Nov 25 '12 at 03:58
  • Thanks everyone, changing sizeof(c) and doing an infile.gcount() has helped. I did notice that when my file is being read, it only reads up until the next return line (hence only one line is read)? – harman2012 Nov 25 '12 at 05:54
  • I had used infile.get() and infile.read(), but infile.read() ignores new lines. – harman2012 Nov 25 '12 at 06:56
0

Try this:

int cont = 0;
while(infile.good()) {
  c[cont++] = infile.get();
}
hinafu
  • 689
  • 2
  • 5
  • 13