Finding end of file while reading from it

后端 未结 5 1069
夕颜
夕颜 2021-01-16 06:09
void graph::fillTable()
{
  ifstream fin;
  char X;
  int slot=0;

  fin.open(\"data.txt\");

  while(fin.good()){

  fin>>Gtable[slot].Name;
  fin>>Gtab         


        
5条回答
  •  南方客
    南方客 (楼主)
    2021-01-16 06:19

    *Edited in response to James' comment - the code now uses a good() check instead of a !eof() check, which will allow it to catch most errors. I also threw in an is_open() check to ensure the stream is associated with the file.*

    Generally, you should try to structure your file reading in a loop as follows:

    ifstream fin("file.txt");
    char a = '\0';
    int b = 0;
    char c = '\0';
    
    if (!fin.is_open())
        return 1; // Failed to open file.
    
    // Do an initial read. You have to attempt at least one read before you can
    // reliably check for EOF.
    fin >> a;
    
    // Read until EOF
    while (fin.good())
    {
        // Read the integer
        fin >> b;
    
        // Read the remaining characters (I'm just storing them in c in this example)
        for (int i = 0; i < b; i++)
            fin >> c;
    
        // Begin to read the next line. Note that this will be the point at which
        // fin will reach EOF. Since it is the last statement in the loop, the
        // file stream check is done straight after and the loop is exited.
        // Also note that if the file is empty, the loop will never be entered.
        fin >> a;
    }
    
    fin.close();
    

    This solution is desirable (in my opinion) because it does not rely on adding random breaks inside the loop, and the loop condition is a simple good() check. This makes the code easier to understand.

提交回复
热议问题