File Input and Output


  1. Declare a file pointer, fi

  2. Using this file pointer, open the text file file.txt for reading only.

  3. Add code to check that the file has been opened correctly.

  4. How would the code for question 2 be changed if you wished to oen the file for writing rather than reading.

  5. Assuming that the file file.txt opened for reading contains a column of integers, give some example to code to read all the numbers into an array.


Answers





























































  1. ifstream fi;

  2. fi.open("file.txt");

  3. if (!fi ) 
    {
             cout << "Can't open file file.txt for reading\n";
             exit(1);
    }
    
  4. oftream fi;

    fi.open("file.txt");

  5. fi >> array[i];
    while (!fi.eof())
    {
    	i++;
    	fi >> array[i];
    }
    


    Back to Questions Back to Main Page for Lecture 8