Concept Flow - File input using ifstream
Open file with ifstream
Check if file opened successfully
Read data
Process data
Close file
This flow shows opening a file, checking success, reading data if open, and closing the file.
#include <iostream> #include <fstream> #include <string> using namespace std; int main() { ifstream file("data.txt"); if (file) { string line; getline(file, line); cout << line << endl; } file.close(); return 0; }
| Step | Action | Evaluation | Result |
|---|---|---|---|
| 1 | Open file with ifstream file("data.txt") | File exists? | File opened successfully |
| 2 | Check if (file) | Is file open? | True, proceed to read |
| 3 | getline(file, line) | Read first line | line = "Hello World" (example) |
| 4 | cout << line | Print line | Output: Hello World |
| 5 | file.close() | Close file | File closed |
| 6 | return 0 | Program ends | Exit normally |
| Variable | Start | After Step 3 | Final |
|---|---|---|---|
| file | not opened | opened and ready | closed |
| line | "" | "Hello World" | "Hello World" |
ifstream file("filename");
if (file) {
getline(file, line); // read line
}
file.close();
Open file, check success, read data, close file.
Always check if file opened before reading.