question archive As we examine files, explain how Input/Output data files work in a program, and how you would use a loop to process input and/or output
Subject:Computer SciencePrice:2.87 Bought7
As we examine files, explain how Input/Output data files work in a program, and how you would use a loop to process input and/or output. Define the differences in a field, record and file, and define what an exception is.
Answer:
A file is a collection of information. There are different types of files like a text file, dat file, binary file, CSV file etc. All these files stores data in one particular format.
The output produced by a program doesn't save unless it is explicitly saved. We use a file to store data, process data, retrieve data to perform some calculations.
The program reads a file and processes it. The way in which information is read depends on the programming language, type of file as well as functions used to process it.
In C/C++, the file pointer needs to be created to hold the file. There are different modes like read, write, append read/write etc. You can read a file line by line, character by character, block by block.
The loop is created which can read a file character by character and it will terminate when End Of File (EOF) is being reached.
Example:
#include<iostream>
#include <fstream>
using namespace std;
int main() {
char str[256];
char c;
cout << "Enter the name of an existing file: ";
cin.get (str,256); // get the file name. File name is limited to 256 characters
ifstream is(str); // FILE OPEN
while (is.get(c)) // read character by character
cout << c;
is.close(); // FILE CLOSE
}
A file is a collection of records. The record is a collection of fields.
A field is one of the attributes in a record.
Example: student.txt
StudentNo StudentName
1 ABC
2 DEF
student.txt is a file.
Student No and StudentName are fields.
1 ABC
2 DEF
records.
An exception is an abnormal condition which leads to abnormal termination of a program. In FILE context, an exception would happen when you try to read a file which doesn't exist when you try to use a function which doesn't work with the specific type of file etc.